[英]Why did to_s in Ruby 1.9.2 change behavior?
It looks like in ruby 1.9.2 if to_s is defined, inspect will return to_s?? 看起来在ruby 1.9.2中,如果定义了to_s,inspect将返回to_s? Why would this change?
为什么会改变?
This: 这个:
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
outputs this: 输出此:
ToSClass to_s called
ToSClass to_s called
InspectClass inspect called
#<InspectClass:0x316baf8>
BothClass inspect called
BothClass to_s called
Object#inspect will call to_s if available. Object#inspect将调用to_s(如果可用)。 I don't think the behavior has changed.
我认为行为没有改变。
I've run your program on 1.9.2 and 1.8.7 and don't see any difference. 我已经在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.