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

Discussion in 'Ruby' started by Martin, Apr 6, 2004.

  1. Martin

    Martin Guest

    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
     
    Martin, Apr 6, 2004
    #1
    1. Advertising

  2. Martin

    Xavier Guest

    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.
     
    Xavier, Apr 6, 2004
    #2
    1. Advertising

  3. Martin

    Martin Hart Guest

    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
     
    Martin Hart, Apr 6, 2004
    #3
  4. Martin

    Martin Guest

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

    martinus
     
    Martin, Apr 7, 2004
    #4
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.

Share This Page