From: Florian Frank Date: 2010-04-29T02:23:57+09:00 Subject: Re: Overload the normal behavior of an object/instance in string On 28/04/2010 19:03, 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. > > [code] > class Test > def inspect > puts "this is a test" > end > end > > p = Test.new > this is a test > >>> p >>> > this is a test > > puts p > # > > >>> "#{p}" >>> > => "#" > [/code] > You should return strings from these methods: class Test def inspect "this is a test" # return the string, don't output it end def to_s "this is another test" end end Then ruby can call Test#inspect or Test#to_s as it desires: p Test.new # outputs: this is a test puts Test.new # outputs: this is another test -- Florian Frank