Jeff Lee
Jeff Lee

Reputation: 1336

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

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.

Upvotes: 4

Views: 5835

Answers (2)

Tyler Eaves
Tyler Eaves

Reputation: 13133

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

Upvotes: 4

Phrogz
Phrogz

Reputation: 303421

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

Upvotes: 5

Related Questions