The Array.to_s
uses inspect
on its content, instead of calling to_s
recursively.
This code
class Some
def to_s; "some" end
end
puts [Some.new].to_s
Would produce [#<Some:0x10078ce80>]
, instead of [some]
Wondering if there could be any bad consequences if I override Array.to_s
to use to_s
recursively? And why it's not working this way by default?
When you stringify a collection, you need every collection item to be self contained in order to distinguish between one and the other. #inspect
takes care of that because it's supposed to stringify the value in an unambiguous way.
For example, if Array#inspect
used #to_s
on the items, the result of ["a", "b,c", 'd'].to_s
would be "[a,b,c,d]"
and you can't tell how many items are even in the collection or what types they have.