How do I add multiple elements to an array?

I can easily add one element to an existing array:

arr = [1]
arr << 2
# => [1, 2]

How would I add multiple elements to my array?

I'd like to do something like arr << [2, 3], but this adds an array to my array #=> [1, [2, 3]]


Solution 1:

Using += operator:

arr = [1]
arr += [2, 3]
arr
# => [1, 2, 3]

Solution 2:

Make use of .push

arr = [1]
arr.push(2, 3)
# => [1, 2, 3]

You can also .push() all elements of another array

second_arr = [2, 3]
arr.push(*second_arr)
# => [1, 2, 3]

But take notice! without the * it will add the second_array to arr.

arr.push(second_arr)
# => [1, [2, 3]]

Inferior alternative:

You could also chain the << calls:

arr = [1]
arr << 2 << 3
# => [1, 2, 3]

Solution 3:

You can do also as below using Array#concat:

arr = [1]
arr.concat([2, 3]) # => [1, 2, 3]