Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to override Ruby's default string interpolation behavior with a method?

Tags:

ruby

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.

like image 835
Jeff Lee Avatar asked Jan 18 '23 05:01

Jeff Lee


2 Answers

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
like image 77
Phrogz Avatar answered Feb 14 '23 18:02

Phrogz


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".

like image 41
Tyler Eaves Avatar answered Feb 14 '23 17:02

Tyler Eaves