From: Dave Thomas Date: 2003-08-06T13:12:04+09:00 Subject: Re: User-defined class coercion? Mark J. Reed wrote: >I would like to define my own class that works as a number when >treated as a number but also has other properties. Can I do this? >If so, how? > > Here's an extract from the new reference material for the coerce method: Coerce is both an instance method of Numeric and part of a type conversion protocol. When a number is asked to perform an operation, and is passed a parameter of class different to its own, it must first coerce both itself and that parameter into a common class so that the operation makes sense. For example, in the expression $1 + 2.5$, the Fixnum ``1'' must be converted to a Float to make it compatible with ``2.5''. This conversion is performed by coerce. For all numeric object, coerce is straightforward: if aNumeric is the same type as self, returns an array containing aNumeric and self. Otherwise, returns an array with both aNumeric and self represented as Float objects. If a numeric object is asked to operate on a non-numeric, it tries to invoke coerce on that other object. For example, if you write: 1 + "2" Ruby will effectively execute the code as: n1, n2 = "2".coerce(1) n2 + n1 In the more general case, this won't work, as most non-numerics don't define a coerce method. However, you can use this (if you feel so inclined) to implement part of Perl's automatic conversion of strings to numbers in expressions. class String def coerce(other) case other when Integer begin return Integer(self), other rescue return Float(self), Float(other) end when Float return Float(self), other else super end end end 1 + "2" 1 + "2.3" 1.2 + "2.3" 1.5 + "2"