On May 29, 11:04 am, Robert Klemme <shortcut... / googlemail.com> wrote: > On 29.05.2007 10:51, kimer... / gmail.com wrote: > > > > > Hi, > > > I'm playing around with ruby trying to understand whats going on, and > > here is something I don't understand. > > > class ZNum > > def initialize(n) > > @n=n > > end > > def to_s > > self.class > > end > > end > > > n = ZNum.new(1234) > > > puts n # prints #<ZNum:0xb75dfcc8> > > puts n.to_s # prints ZNum > > > In both cases it uses ZNum#to_s, but the results are different. Why? > > 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. /kim