我不明白以下代码为什么会引发异常:
class X
def to_s
"x"
end
end
s = ""
s << X.new
# --> TypeError: can't convert X into String
毕竟,'to_s'应该将X转换为字符串。
class X
def to_s
"x"
end
end
s = ""
s << X.new
# --> TypeError: can't convert X into String
毕竟,'to_s'应该将X转换为字符串。
to_str
也就是说,如果您在类中添加 def to_str; "x"; end
,<<
表达式将自动进行转换。毕竟,
to_s
应该将X
转换为String
。
不是的,它应该把它表示成一个 String
。 to_str
才是应该将其转换的方法。
s << X.new.to_s