f



["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
0
4/6/2004 11:23:22 AM
comp.lang.ruby 48886 articles. 0 followers. Post Follow

3 Replies
481 Views

Similar Articles

[PageSpeed] 27

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.
0
NOSPAM2312 (18)
4/6/2004 11:29:08 AM
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



0
martin4484 (31)
4/6/2004 12:16:20 PM
> can't you just use join?
Thanks! Somehow I have never seen this method...

martinus
0
4/7/2004 2:11:03 PM
Reply: