How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

Viewed 479836

I tried:

somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray.push(anotherarray.flatten!)

I expected

["some", "thing", "another", "thing"]

but got

["some", "thing", nil]
18 Answers
a = ["some", "thing"]
b = ["another", "thing"]

To append b to a and store the result in a:

a.push(*b)

or

a += b

In either case, a becomes:

["some", "thing", "another", "thing"]

but in the former case, the elements of b are appended to the existing a array, and in the latter case the two arrays are concatenated together and the result is stored in a.

a = ['a', 'b']
b = ['c', 'd']
arr = [a, b].flatten

This won't remove dups, but

a|b

removes dups.

somearray = ["some", "thing"]

anotherarray = ["another", "thing"]

somearray + anotherarray

somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray + anotherarray # => ["some", "thing", "another", "thing"]
somearray.concat anotherarray # => ["some", "thing", "another", "thing"]
somearray.push(anotherarray).flatten # => ["some", "thing", "another", "thing"]
somearray.push *anotherarray # => ["another", "thing", "another", "thing"]
 
Related