Reputation: 2131
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 --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?
Upvotes: 4
Views: 126
Reputation: 22385
You don't need to_s
. puts
does the work for you
puts [Test.new(), Test.new()]
# hi
# hi
If you want the brackets, that's what inspect
is for (in which case it makes sense that you would need to define Test#inspect
).
Upvotes: 0
Reputation: 160621
Your code:
puts [Test.new(), Test.new()].to_s
is a questionable use of Array.to_s
. Instead I'd use:
puts [Test.new(), Test.new()].map(&:to_s)
While I can see that the first use makes sense, the second use makes more sense and should work in any version of Ruby.
Upvotes: 5
Reputation: 15171
On 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]
This seems like a bug to me. If it is intended behavior, that is really annoying.
Upvotes: 1