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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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_strThat is, if you add
def to_str; "x"; endto your class the<<expression will work with an automatic conversion.