Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why's that? Can't convert into String: I do have a to_s method!

Tags:

ruby

I don't understand why the following raises an exception:

class X
  def to_s
    "x"
  end
end

s = ""
s << X.new
# --> TypeError: can't convert X into String

After all 'to_s' is supposed to convert X into a String.

like image 926
radiospiel Avatar asked Dec 12 '22 12:12

radiospiel


1 Answers

The short conversions aren't called automatically by the Ruby core; that's what the long conversions are for. The long conversions are intended for things that are very much like the conversion target already, as opposed to things that simply have a representation of the target type.

Use: to_str

That is, if you add def to_str; "x"; end to your class the << expression will work with an automatic conversion.

like image 69
DigitalRoss Avatar answered Mar 16 '23 12:03

DigitalRoss