Neither to_s
nor to_str
appear to get called when an object is referenced inside a double-quoted string interpolation. For example:
# 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 suppose there's something I can do to make the return value "foo"
?
UPDATE
Apologies, but this code actually works. Mistake in another piece of code.
With what version of Ruby are you seeing 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
You're not returning a string. Remove the puts
, since to_s
needs to RETURN a string representation, not output it.
Note: this response is based on a previous version of the question where the to_s
method had the code puts "foo"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With