Is there a way to override the default Ruby string interpolation behavior using a method?

Neither to_s nor to_str appear to be called when the object is referenced inside to_str string interpolation. For instance:

 # UPDATE: This example actually works as expected. See update below. class Foo def to_s 'foo' end def to_str to_s end end "#{Foo.new}" # result: "#<Foo:0x007fb115c512a0>" 

I don’t think what I can do to make the return value "foo" ?

UPDATE

Sorry, but this code really works. Error in another piece of code.

+4
source share
2 answers

With which version of Ruby do you see these results? This works correctly for me with Ruby 1.9.2 and 1.8.6:

 class Foo def to_s 'hi mom' end end puts "#{Foo.new}" #=> hi mom 
+5
source

You are not returning a string. Delete puts , since to_s should RETURN the string representation, and not output it.

Note: this answer is based on a previous version of the question, where the to_s method had the code puts "foo" .

+4
source

Source: https://habr.com/ru/post/1401236/


All Articles