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]]
If you want to add multiple elements to the array at once, you can think of initializing the array with multiple elements or convert the array to ArrayList. ArrayList has an 'addAll' method that can add multiple elements to the ArrayList.
If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat().
Using +=
operator:
arr = [1] arr += [2, 3] arr # => [1, 2, 3]
.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]
You can do also as below using Array#concat
:
arr = [1]
arr.concat([2, 3]) # => [1, 2, 3]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With