The # to_s array in Ruby 2.1 broke my code

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? How to keep the previous behavior?

+4
source share
3 answers

Your code:

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

is a dubious use Array.to_s. Instead, I would use:

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

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

+5
source

In 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 mistake to me. If this is the intended behavior, it is really annoying.

+1
source

to_s. puts

puts [Test.new(), Test.new()]
# hi
# hi

, inspect ( Test#inspect).

0

Source: https://habr.com/ru/post/1568041/


All Articles