From: Brian Candler Date: 2007-05-29T22:02:48+09:00 Subject: Re: Overriding to_s On Tue, May 29, 2007 at 09:55:04PM +0900, kimersen@gmail.com wrote: > > Because puts will revert to something else (likely #inspect) if the > > result of to_s is not String. > > > > irb(main):001:0> class Foo > > irb(main):002:1> def to_s; self.class.to_s end > > irb(main):003:1> end > > => nil > > irb(main):004:0> puts Foo.new > > Foo > > => nil > > > > Kind regards > > > > robert > > My understanding of puts is that it puts the result of to_s. > puts n and puts n.to_s are the same then and should in my example > print the same. > But they don't and that is for me a bit annoying because I thought I > understood what was going on. Yes, but what do you expect "puts" to do when it calls to_s on an object, but the result is not a string? Raise an exception perhaps? It's more friendly for puts to have a fallback behaviour. Note: there's one other special case I'm aware of. If you do puts nil then you get the string "nil" printed (plus newline). However, nil.to_s is the empty string. Regards, Brian.