iconoclast
iconoclast

Reputation: 22670

In Ruby how can I add a nested array to an array without creating an additional layer of nesting?

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?

Upvotes: 1

Views: 180

Answers (1)

Beno&#238;t
Beno&#238;t

Reputation: 15010

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]]

Upvotes: 2

Related Questions