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

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 08/13/2013 06:20 AM, Kaspar Schiess wrote:

Hi everyone

Who has a good explanation for the output of this:

     Non-obvious string interpolation tidbit. · GitHub

?

regards,
kaspar

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

···

On Tue, Aug 13, 2013 at 11:11 AM, Justin Collins <justincollins@ucla.edu> 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.

--
Dave Aronson, the T. Rex of Codosaurus LLC,
secret-cleared freelance software developer
taking contracts in or near NoVa or remote.
See information at http://www.Codosaur.us/\.