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

M

Martin

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
 
X

Xavier

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.
 
M

Martin Hart

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
 
M

Martin

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

martinus
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top