让自定义.to_s在数组中工作

时间:2013-12-03 20:21:14

标签: ruby

我有一个自定义类.to_s方法。在单个对象上调用.to_s可以正常工作,但是如果我在所述对象的数组上调用.to_s,我只得到哈希标记:

class Custom
  def to_s
    'custom thing'
  end
end

c1 = Custom.new
c1.to_s # => 'custom thing'
c2 = Custom.new
c3 = Custom.new
[c1,c2,c3].to_s # => [#,#,#]

如何让我的自定义.to_s使用数组项?

3 个答案:

答案 0 :(得分:4)

覆盖inspect

class Custom
  def inspect
    'custom thing'
  end
end

c1 = Custom.new
c2 = Custom.new
c3 = Custom.new
[c1,c2,c3].to_s # => "[custom thing, custom thing, custom thing]"

答案 1 :(得分:1)

这是您使用map

的地方
c1 = Custom.new
c1.to_s # => 'custom thing'

c2 = Custom.new
c3 = Custom.new

[c1,c2,c3].map(&:to_s) # => ['custom thing','custom thing','custom thing']

答案 2 :(得分:1)

Array上的默认to_s现在是inspect的别名,同样适用于所有包含的对象,但是在Ruby 1.8中它等同于join(' ')并且称为{{1在元素上。

一般情况下,你不应该在Array或Hash对象上使用to_s,输出总是很乱。

to_s