Gary Wright
10/21/2006 9:05:00 PM
On Oct 20, 2006, at 12:57 AM, Yukihiro Matsumoto wrote:
> The official purpose of #to_s method is that returning string
> representation of the object. No more, no less. So it's up to our
> expectation for the string representation of the object. I changed
> the behavior to make string representation of arrays more
> distinguishable from other objects.
>
> I don't think to_s _SHOULD_ work as replacement of Array#join. But
> there may be another reason I missed to keep it compatible with 1.8.
OK, I grabbed ruby 1.9 so that I could actually play with it.
I always assumed that Array#join simply called Array#to_s on each
element
and then constructed the final string by inserting the separator between
each element, but it actually seems to flatten the array first:
Ruby 1.8:
a = [1,2]
b = [3,4]
c = [a,'foo',b]
c.to_s # 12foo34
c.inspect # [[1, 2], "foo", [3, 4]]
c.join # 12foo34
c.join('-') # 1-2-foo-3-4
When the separator is the empty string, the two algorithms are the
same, but
if the separator is not empty then they give different results. The
non-flattening algorithm would produce: 12-foo-34 in the above example.
My objections to the Array#to_s behavior in 1.9 were based on
thinking about
Array#join as simply calling #to_s on each element (without the
flattening step),
which would make it more difficult to work around.
So in 1.9, the above example produces:
c.to_s # [[1, 2], "foo", [3, 4]]
c.inspect # [[1, 2], "foo", [3, 4]]
c.join # 12foo34
c.join('-') # 1-2-foo-3-4
I think the documentation for Array#join should mention the
flattening step.
Something like:
Returns a string created by flattening the array, converting
each element of
the result to a string via #to_s, and concatenating the strings
with _sep_ as
the separator.
Gary Wright