Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > ["a", "b", "c", "d"] to "a, b, c, d"?

Reply
Thread Tools

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

 
 
Martin
Guest
Posts: n/a
 
      04-06-2004
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
 
Reply With Quote
 
 
 
 
Xavier
Guest
Posts: n/a
 
      04-06-2004
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


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


Hth.
 
Reply With Quote
 
 
 
 
Martin Hart
Guest
Posts: n/a
 
      04-06-2004
On Tuesday 06 Apr 2004 12:24 pm, 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?
>


can't you just use join?

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

or have i misunderstood you?

Cheers,
Martin

> martinus


--
Martin Hart
Arnclan Limited
Union Street, Dunstable, LU6 1EX
http://www.arnclan.com



 
Reply With Quote
 
Martin
Guest
Posts: n/a
 
      04-07-2004
> can't you just use join?
Thanks! Somehow I have never seen this method...

martinus
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off




Advertisments