Carlos
9/22/2006 1:04:00 AM
Robert Klemme wrote:
> Bart Braem <bart.braem@gmail.com> wrote:
>
>> Robert Klemme wrote:
>>
>>> Granted, the version using to_s is certainly questionable but the
>>> other two alternatives (especially p, which uses #inspect
>>> internally) are pretty clear, aren't they?
>>
>>
>> They sure are, but some projects, in this case Rails, seem to use the
>> to_s method.
>
>
> I have no insight at which exact point it does this. But I guess you
> can change that, or explicitly invoke another method.
>
>> And I don't understand why that remove-all-spaces
>> approach is chosen.
>
>
> Probably because it is not a "remove all spaces" approach: there are no
> spaces in an array, Array#to_s just appends string representations of
> all its elements. It's like Array#join called without arguments (or
> with an empty string as argument). :-)
>
>> But perhaps there are good reasons for this, I'm
>> not a longtime ruby user so I just wonder.
>
>
> My guess at the reasoning behind this goes like this: to_s does the
> simplest thing possible (i.e. converting all elements to string via
> their #to_s and then concatenate them). If the user wants something
> more fancy, she has to explicitly use another method, e.g. join with an
> argument that denotes the string that is inserted in between.
You can just set $, to the separator you want.
$ ruby -e '$,=","; puts [1,2,3,4].to_s'
1,2,3,4
It's also the default argument to #join.
--