这是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
答案 0 :(得分:2)
这不起作用,因为puts
仅对不是字符串的内容调用to_s
。在你的情况下'hello
'已经是一个字符串,因此puts
不需要在其上调用to_s
(puts
也包含其他一些类的显式实现,例如数组)
另一方面,如果你已经在一个不是String的东西上定义了一个to_s
方法,那么应该调用你的to_s方法
class Foo
def to_s
'hello world'
end
end
puts Foo.new
将输出' hello world'。