["a", "b", "c", "d"] to "a, b, c, d"?

I want to process each element of an array, but the last element
should be handled special. Here is an example:

def p_ary(ary)
str = ""
ary.each do |elem|
str << elem << ", “
end
str.chomp!(”, ")
str
end

so p_ary([“a”, “f”, “x”, “test”]) produces “a, f, x, test”. The code
works, but isn’t there an easier and more general way for this
behaviour?

martinus

[“a”, “f”, “x”, “test”].join(", ")
=> “a, f, x, test”

Hth.

···

On Tue, 06 Apr 2004 04:23:22 -0700, Martin wrote:

I want to process each element of an array, but the last element
should be handled special. Here is an example:

def p_ary(ary)
str = “”
ary.each do |elem|
str << elem << “, "
end
str.chomp!(”, ")
str
end

so p_ary([“a”, “f”, “x”, “test”]) produces “a, f, x, test”. The code
works, but isn’t there an easier and more general way for this
behaviour?

martinus

I want to process each element of an array, but the last element
should be handled special. Here is an example:

def p_ary(ary)
str = “”
ary.each do |elem|
str << elem << “, "
end
str.chomp!(”, ")
str
end

so p_ary([“a”, “f”, “x”, “test”]) produces “a, f, x, test”. The code
works, but isn’t there an easier and more general way for this
behaviour?

can’t you just use join?

def p_ary(ary)
ary.join(", ")
end

or have i misunderstood you?

Cheers,
Martin

···

On Tuesday 06 Apr 2004 12:24 pm, Martin wrote:

martinus


Martin Hart
Arnclan Limited
Union Street, Dunstable, LU6 1EX

can’t you just use join?
Thanks! Somehow I have never seen this method…

martinus