B
Benoit Daloze
[Note: parts of this message were removed to make it a legal post.]
Hi,
I got recently an unexpected result using Array#join.
In my thoughts, Array#join is sth like adding the separator between every
element#to_s.
That is what seems to happen when there is no any #to_a method defined in an
element:
For example,
class N < Struct.newn)
def to_s
'to_s'
end
end
[N.new(2), N.new(3)].join(' ') #=> "2 3" and not "to_s to_s"
This is due to Struct::new that defines #to_a that return an Array of
instance variables (here :n).
That's quite annoying, because you would expect when you're defining to_s to
be the only usual String representation.
The only way to edit that behavior without changing Array#join, is to
"undef_method :to_a", not very nice ...
or to use ary.map(&:to_s).join, very redundant.
Shouldn't Array#join looks like:
class Array
def join(sep = $,)
sep = '' if sep.nil?
s = ""
self.each_with_index { |e, i|
s << e.to_s
s << sep unless i == size-1
}
s
end
end
Why is it this 'look' to element#to_a ? is that really interesting? when?
Maybe when you use [[1],[2,3]].join #=> "123" ? Then we should look for
#to_ary, not #to_a
Regards,
B.D.
Hi,
I got recently an unexpected result using Array#join.
In my thoughts, Array#join is sth like adding the separator between every
element#to_s.
That is what seems to happen when there is no any #to_a method defined in an
element:
For example,
class N < Struct.newn)
def to_s
'to_s'
end
end
[N.new(2), N.new(3)].join(' ') #=> "2 3" and not "to_s to_s"
This is due to Struct::new that defines #to_a that return an Array of
instance variables (here :n).
That's quite annoying, because you would expect when you're defining to_s to
be the only usual String representation.
The only way to edit that behavior without changing Array#join, is to
"undef_method :to_a", not very nice ...
or to use ary.map(&:to_s).join, very redundant.
Shouldn't Array#join looks like:
class Array
def join(sep = $,)
sep = '' if sep.nil?
s = ""
self.each_with_index { |e, i|
s << e.to_s
s << sep unless i == size-1
}
s
end
end
Why is it this 'look' to element#to_a ? is that really interesting? when?
Maybe when you use [[1],[2,3]].join #=> "123" ? Then we should look for
#to_ary, not #to_a
Regards,
B.D.