[Ruby] Java-like toString() method?

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.

HTH

Stephan

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 :slight_smile:

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 :slight_smile:

···

On Sun, Mar 30, 2003 at 07:47:57AM +0900, Stephan Kämper wrote:

I still think to_s is the right thing.
Having a string like “bla\n” inspected you get the newline escaped,
instead of a real new line.

Just, while java println knows how to handle various types, puts or
print need strings, and I think this is The Right Thing ™

···

il Sun, 30 Mar 2003 10:28:30 +0200, “Frank Thomas” root@sparkynet.de ha scritto::

Test t = new Test();
System.out.print(t); // → “This is a test-class”

I believe the inspect() method is the equivalent in ruby. (By the way: i