gpt4 book ai didi

ruby - 为什么 Ruby 1.9.2 中的 to_s 改变了行为?

转载 作者:太空宇宙 更新时间:2023-11-03 18:31:23 25 4
gpt4 key购买 nike

看起来在 ruby​​ 1.9.2 中,如果定义了 to_s,inspect 将返回 to_s??为什么会发生这种变化?

这个:

class ToSClass
def to_s
"#{self.class.name} to_s called"
end
end
class InspectClass
def inspect
"#{self.class.name} inspect called"
end
end
class BothClass
def inspect
"#{self.class.name} inspect called"
end
def to_s
"#{self.class.name} to_s called"
end
end

c1 = ToSClass.new
puts c1.inspect
puts c1.to_s
c1 = InspectClass.new
puts c1.inspect
puts c1.to_s
c1 = BothClass.new
puts c1.inspect
puts c1.to_s

输出这个:

ToSClass to_s called
ToSClass to_s called
InspectClass inspect called
#<InspectClass:0x316baf8>
BothClass inspect called
BothClass to_s called

最佳答案

如果可用,Object#inspect 将调用 to_s。我认为行为没有改变。

我已经在 1.9.2 和 1.8.7 上运行了你的程序,没有发现任何区别。

$ rvm inspect.rb 1.9.2,1.9.1,1.8.7

info: 1.9.2 (ruby-1.9.2-p0): ruby 1.9.2p0 (2010-08-18 revision 29036) [x86_64-linux]

ToSClass to_s called
ToSClass to_s called
InspectClass inspect called
#<InspectClass:0x00000001941c80>
BothClass inspect called
BothClass to_s called

info: 1.9.1 (ruby-1.9.1-p378): ruby 1.9.1p378 (2010-01-10 revision 26273) [x86_64-linux]

ToSClass to_s called
ToSClass to_s called
InspectClass inspect called
#<InspectClass:0x000000011594b8>
BothClass inspect called
BothClass to_s called

info: 1.8.7 (ruby-1.8.7-p302): ruby 1.8.7 (2010-08-16 patchlevel 302) [x86_64-linux]

ToSClass to_s called
ToSClass to_s called
InspectClass inspect called
#<InspectClass:0x7ffd795afd60>
BothClass inspect called
BothClass to_s called

关于ruby - 为什么 Ruby 1.9.2 中的 to_s 改变了行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3553146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com