Ruby 2.1中的数组#to_s打破了我的代码
这段代码打破了Ruby 2.1
class Test def to_s() "hi" end end puts [Test.new(), Test.new()].to_s
Ruby 1.9.3:
$ ruby --version ruby 1.9.3p484 (2013-11-22 revision 43786) [x86_64-linux] $ /opt/chef/embedded/bin/ruby test.rb [hi, hi]
Ruby 2.1:
$ ruby --version ruby 2.1.4p265 (2014-10-27 revision 48166) [x86_64-linux] $ ruby test.rb [#, #]
这是在某处记录的吗? 如何保留旧的行为?
你的代码:
puts [Test.new(), Test.new()].to_s
是一个有问题的使用Array.to_s
。 相反,我会使用:
puts [Test.new(), Test.new()].map(&:to_s)
虽然我可以看到第一次使用有意义,但第二次使用更有意义,并且应该适用于任何版本的Ruby。
关于ruby 2.1.5:
class Test def to_s "hi" end alias inspect to_s # add this line end puts [Test.new, Test.new].to_s #=> [hi, hi]
这对我来说似乎是个错误。 如果是预期的行为,那真的很烦人。
你不需要to_s
。 puts
为你工作
puts [Test.new(), Test.new()] # hi # hi
如果你想要括号,那就是inspect
目的(在这种情况下你需要定义Test#inspect
)。