5.16. Coercing Numeric Values
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 end
The 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 ...
Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.