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