Lesson 18 of 23 · Ruby 4.1 development
Define an operator for your objects
Implement + as a method that combines two instances.
Development course: behavior may change with future runtime updates.
Learn
Many Ruby operators are methods. The expression left + right calls the + method on left and passes right as its argument, just like left.+(right). Defining def +(other) lets your class give that operator a useful meaning.
Distance#+ combines the meters held by two Distance objects and returns a new Distance. Its reader method lets one object read the other object's meters. The implementation expects another Distance and leaves both operands unchanged. Defining an operator does not change its precedence.
Example
class Distance
attr_reader :meters
def initialize(meters)
@meters = meters
end
def +(other)
Distance.new(meters + other.meters)
end
end
left = Distance.new(4)
right = Distance.new(6)
total = left + right
p total.meters
p left.metersExperiment
Predict both totals. Replace the operator expression with left.+(right) and check whether it changes the result.
Predict the total and both original values. Add a fourth Distance to the expression and explain why chaining is possible.