From: Rick DeNatale Date: 2010-04-29T02:27:04+09:00 Subject: Re: Overload the normal behavior of an object/instance in string On Wed, Apr 28, 2010 at 1:03 PM, Walle Wallen wrote: > Long story short. I'm trying to overload the normal behavior of an > object/instance in a string. Instead of replying "" I > would like it too return a specific string, or something similar. I have > tried to overload inspect, and it seems to work pretty well, except when > using the object with puts or in a string "#{p}". > > My english ain't good, but I hope you understand the principle of what I > am trying to achieve. There are two different methods which Ruby uses to get a printstring from an object, both of which should return a String. inspect produces a 'programmer friendly' printstring in general, while to_s produces a 'user friendly' string. There's a Kernel method p which is roughly equvalent to: def p(arg) puts arg.inspect end puts just uses to_s to convert non-strings to strings. And irb displays the the value of inspect after evaluating an expression. > [code] > class Test >  def inspect >     puts "this is a test" >  end This should simply return the string, you don't always want to puts the result, and puts will cause the result to be nil, not the string. > end > > p = Test.new > this is a test >>> p > this is a test > > puts p > # > >>> "#{p}" > => "#" > [/code] Try this: class Test def inspect "this is a test inspection" end def to_s "this is a test" end end p = Test.new puts p puts "#{p}" puts p.inspect which produces: this is a test this is a test this is a test inspection -- Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Github: http://github.com/rubyredrick Twitter: @RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale