Ruby 2.1中的Array#to_s破坏了我的代码 [英] Array#to_s in Ruby 2.1 broke my code

查看:100
本文介绍了Ruby 2.1中的Array#to_s破坏了我的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码在Ruby 2.1上中断

This code broke on Ruby 2.1

class Test
  def to_s()
    "hi"
  end
end

puts [Test.new(), Test.new()].to_s

Ruby 1.9.3:

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
[#<Test:0x000000022ac400>, #<Test:0x000000022ac3d8>]

此文件记录在某处吗?如何保留旧的行为?

Is this documented somewhere? How can the old behavior be preserved?

推荐答案

您的代码:

puts [Test.new(), Test.new()].to_s

Array.to_s的可疑用法.相反,我会使用:

is a questionable use of Array.to_s. Instead I'd use:

puts [Test.new(), Test.new()].map(&:to_s)

虽然我可以看到第一种用法很有意义,但是第二种用法更有意义,并且可以在任何版本的Ruby中使用.

While I can see that the first use makes sense, the second use makes more sense and should work in any version of Ruby.

这篇关于Ruby 2.1中的Array#to_s破坏了我的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆