Ruby Programming Language (coerce)

December 02, 2008

Reading the Ruby Programming Language which seems excellent so far. So may well do a number of blog posts about bits of it just to reenforce my memory

coerce

Method used by numeric types. Idea is to force argument into a suitable type so that the calling type can work with it. Method returns array of two values, the first being the converted value. Some irb will illustrate

>> require 'rational'                                                                 
>> r = Rational(2,1)
>> r.coerce(2)
=> [Rational(2, 1), Rational(2, 1)]

My initial thought was that a.coerce(b) == b.coerce(a). This is completely wrong as shown below

>> 2.coerce r
=> [2.0, 2.0]

coerce is all about convenience for the class it is defined for. So Rational(x,y).coerce is all about making things easy for Rational to do things, whilst Float.coerce is all about making things easy for Float to do things. I’m labouring this point quite a bit, because I don’t think the book made this quite clear enough for my slow brain to grok without a bit of further investigation.