1

I'm trying to do something roughly analogous to this

collection = []
pair_one = [[:ae1,:be1],[:ae2,:be2]]
collection << pair_one
pair_two = [[:ae3,:be3],[:ae4,:be4]]
collection << pair_two

The problem is that collection is this:

[[[:ae1, :be1], [:ae2, :be2]], [[:ae3, :be3], [:ae4, :be4]]] 

and I want it to be this:

[[:ae1, :be1], [:ae2, :be2], [:ae3, :be3], [:ae4, :be4]]

What method should I use instead of <<?

Basically I want to add the contents of pair_one and pair_two to collection, rather than the arrays themselves. What array method is escaping my memory?

2
  • 1
    I don't understand the question. Your "I want it to be this" is not a valid Ruby array. The first example is exactly what you should be getting back from your code. Commented Nov 7, 2012 at 2:53
  • whoops... just a sec and I'll fix it Commented Nov 7, 2012 at 2:54

1 Answer 1

2

You can use concat, += or |=

concat to avoid unnecessary object creation.
|= to eliminate duplicates.

collection = []
#=> []
pair_one = [[:ae1,:be1],[:ae2,:be2]]
collection += pair_one
#=> [[:ae1, :be1], [:ae2, :be2]]
pair_two = [[:ae3,:be3],[:ae4,:be4]]
collection += pair_two
#=> [[:ae1, :be1], [:ae2, :be2], [:ae3, :be3], [:ae4, :be4]]
Sign up to request clarification or add additional context in comments.

7 Comments

@iconoclast: But +1 to you for asking such a nice question ^_^
There's also Array#concat, which creates fewer objects because it modifies the original array in place.
@x1a4: I think += is overloaded to do exactly the same thing (modify the original array in place), so there should be no difference performance-wise.
@NiklasB. The docs are saying + returns a new array. If you are aware otherwise, I'd like to find that documentation.
@x1a4: I was talking about +=, not +. I thought that += is overloaded like in Python, but that doesn't seem to be the case, as a quick test in IRB shows
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.