为什么我必须显式地而不是隐式地调用重写的to_s方法,就像我期望的put一样

时间:2015-01-23 15:03:21

标签: ruby override irb

这是irb会话,我已经覆盖了String类的to_s,但必须明确调用to_s

➜ irb
2.2.0 :001 > class String
2.2.0 :002?>   def to_s
2.2.0 :003?>     swapcase
2.2.0 :004?>     end
2.2.0 :005?>   end
 => :to_s
2.2.0 :006 > puts 'hello'
hello
 => nil
2.2.0 :007 > p 'hello'
"hello"
 => "hello"
2.2.0 :008 > puts 'hello'.to_s
HELLO
 => nil

1 个答案:

答案 0 :(得分:2)

这不起作用,因为puts仅对不是字符串的内容调用to_s。在你的情况下'hello'已经是一个字符串,因此puts不需要在其上调用to_sputs也包含其他一些类的显式实现,例如数组)

另一方面,如果你已经在一个不是String的东西上定义了一个to_s方法,那么应该调用你的to_s方法

class Foo
  def to_s
    'hello world'
  end
end
puts Foo.new

将输出' hello world'。