From: Martin Weber Date: 2003-03-30T09:11:09+09:00 Subject: Re: [Ruby] Java-like toString() method? On Sun, Mar 30, 2003 at 07:47:57AM +0900, Stephan K�mper wrote: > Frank Thomas wrote: > >In Java one can define a toString() method which will return a certain > >string when printing an instance of the object containing the toString() > >method. > > > >Is there anything like that in Ruby? > > > > Hi Frank, > > I think to_s is what's called when you print an object. Actually I think it's inspect, not to_s - that is depending on what the question was *exactly* > 1 1 > class Fixnum > def inspect > "Ruby is %d times more fun than Java!" % self > end > def to_s > "Java is %d times more fun than Ruby!" % self > end > def lies > "#{self}" > end > end nil > 1000 Ruby is 1000 times more fun than Java! > 1000.lies "Java is 1000 times more fun than Ruby!" You see the principle of least surpries applies here, too :) to_s is being used when you want to interpolate an object into a string, as above in the lies method. When you define a to_s method though and wonder why irb keeps ignoring it, well, what is being printed when it should put out something's return value is its inspect method. -Martin :)