为什么?无法转换为String:我有一个to_s方法!

时间:2022-10-30 08:32:10

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.

毕竟'to_s'应该将X转换为String。

3 个解决方案

#1


8  

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.

Ruby核心不会自动调用短转换;这就是长时间的转换。长转换适用于与转换目标非常相似的事物,而不是仅仅具有目标类型表示的事物。

Use: to_str

使用:to_str

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

也就是说,如果你添加def to_str; “X”;结束你的类< <表达式将使用自动转换。< p>

#2


6  

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

毕竟to_s应该将X转换为String。

No, it's not. It is supposed to represent it as a String. to_str is supposed to convert it.

不,这不对。它应该表示为String。 to_str应该转换它。

#3


-1  

There is not any automatic cast in Ruby ; you have to call explicitly your method to_s:

Ruby中没有自动转换;你必须明确调用你的方法to_s:

s << X.new.to_s

#1


8  

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.

Ruby核心不会自动调用短转换;这就是长时间的转换。长转换适用于与转换目标非常相似的事物,而不是仅仅具有目标类型表示的事物。

Use: to_str

使用:to_str

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

也就是说,如果你添加def to_str; “X”;结束你的类< <表达式将使用自动转换。< p>

#2


6  

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

毕竟to_s应该将X转换为String。

No, it's not. It is supposed to represent it as a String. to_str is supposed to convert it.

不,这不对。它应该表示为String。 to_str应该转换它。

#3


-1  

There is not any automatic cast in Ruby ; you have to call explicitly your method to_s:

Ruby中没有自动转换;你必须明确调用你的方法to_s:

s << X.new.to_s