From: Brian Candler Date: 2003-05-31T06:34:33+09:00 Subject: Re: to_s and concatenation On Sat, May 31, 2003 at 06:13:36AM +0900, Anders Borch wrote: > hmm... it seems to me that the real question is this: why have both to_s > and to_str when the return value of them should at all concievable (to > me at least) times be the same? I think the rationale is something like this: You have a method for explicitly converting an object to a string for display purposes: 5.to_s #>> "5" But you might not want to have an automatic, implicit conversion to a string in all circumstances: "10" + 5 #>> should this be "105" or "15" or 15 ? 5 + "10" #>> what about this: "510" or "15" or 15 ? So I believe that to_s is for cases where you explicitly require a conversion to be made, such as foo.to_s or "#{foo}" On the other hand, to_str is for cases where an implicit, automatic conversion should take place. If you don't define it, then such automatic conversions do not take place, so you get an exception instead. irb(main):001:0> "10" + 5 TypeError: failed to convert Fixnum into String from (irb):1:in +' from (irb):1 irb(main):002:0> class Fixnum; def to_str; to_s; end; end => nil irb(main):003:0> "10" + 5 => "105" The same distinction doesn't seem to hold for to_int and to_i though - you get a different exception. I don't understand the mechanics of coercion of numeric types. Regards, Brian.