Please explain: Weird to_s behaviour

Hi everyone

Who has a good explanation for the output of this:

https://gist.github.com/kschiess/6218466

?

regards,
kaspar

On 08/13/2013 06:20 AM, Kaspar S. wrote:

Not sure about a “good” explanation, since I don’t quite understand the
C code which handles string interpolation.

However, it is clear that Ruby does call Foo#to_s (try inserting a
“puts”). However, when Foo#to_s doesn’t return a string, then Ruby falls
back on its default object representation instead of converting that
value to a string. I suspect this is to avoid infinite loops of
conversion attempts:

class Foo
def to_s
Bar.new
end
end

class Bar
def to_s
Foo.new
end
end

-Justin

On Tue, Aug 13, 2013 at 11:11 AM, Justin C.
[email protected] wrote:

when Foo#to_s doesn’t return a string, then Ruby falls back on its
default object representation instead of converting that value to a string.

Excellent catch! If you change the 1 to “1” (i.e., make it a string),
then the 1 shows up instead of the ugly default object representation.

-Dave