Adding elements of one array to another

Discussion in 'Ruby' started by Ari Brown, Aug 29, 2007.

  1. Ari Brown

    Ari Brown Guest

    I can't remember who asked this a while ago, but while I was
    stumbling through my Programming Ruby book, I found a nice method in
    array that will instantly do the trick: Array#concat


    a = [1, 2]
    b = [3, 4]
    a.concat(b) #=> [1, 2, 3, 4]

    I can't remember if someone already posted this solution, but if not,
    here it is.

    Ari
    -------------------------------------------|
    Nietzsche is my copilot
     
    Ari Brown, Aug 29, 2007
    #1
    1. Advertisements

  2. Ari Brown

    Todd Benson Guest

    There's also a+=b. I'm not sure if there's a difference.

    Todd
     
    Todd Benson, Aug 29, 2007
    #2
    1. Advertisements

  3. There is. a += b --> a = a + b, and a + b will always allocate a new
    array. a.concat(b) will try to use any space already allocated in a,
    and only if there is not enough will it regrow a.
     
    Logan Capaldo, Aug 29, 2007
    #3
  4. And note that concat has side effects:

    irb(main):001:0> a = [1,2]
    => [1, 2]
    irb(main):002:0> b = [3,4]
    => [3, 4]
    irb(main):003:0> c = a
    => [1, 2]
    irb(main):004:0> a += b
    => [1, 2, 3, 4]
    irb(main):005:0> c
    => [1, 2]
    irb(main):006:0> a = [1,2]
    => [1, 2]
    irb(main):007:0> b = [3,4]
    => [3, 4]
    irb(main):008:0> c = a
    => [1, 2]
    irb(main):009:0> a.concat(b)
    => [1, 2, 3, 4]
    irb(main):010:0> c
    => [1, 2, 3, 4]
     
    Joel VanderWerf, Aug 29, 2007
    #4
  5. Ari Brown

    Elad Meidar Guest



    You can also use OR to uniquely concat those arrays.
    irb(main):003:0> [1,2] | [3,4]
    => [1, 2, 3, 4]
    irb(main):004:0> [1,2] | [2,3,4]
    => [1, 2, 3, 4]
    irb(main):005:0>
     
    Elad Meidar, Aug 30, 2007
    #5
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.