October 2006
Intermediate to advanced
888 pages
16h 55m
English
Coercion can be thought of as another form of implicit conversion. When a method (+ for example) is passed an argument it doesn’t understand, it tries to coerce the receiver and the argument to compatible types and then do the addition based on those types. The pattern for using coerce in a class you write is straightforward:
class MyNumberSystem
def +(other)
if other.kind_of?(MyNumberSystem)
result = some_calculation_between_self_and_other
MyNumberSystem.new(result)
else
n1, n2 = other.coerce(self)
n1 + n2
end
end
endThe value returned by coerce is a two-element array containing its argument and its receiver converted to compatible types.
In this example, we’re relying on the type of our argument to perform some ...
Read now
Unlock full access