How do I add multiple elements to an array?
ArraysRubyArrays Problem Overview
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]]
Arrays Solutions
Solution 1 - Arrays
Using +=
operator:
arr = [1]
arr += [2, 3]
arr
# => [1, 2, 3]
Solution 2 - Arrays
.push
Make use of 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 - Arrays
You can do also as below using Array#concat
:
arr = [1]
arr.concat([2, 3]) # => [1, 2, 3]
Solution 4 - Arrays
There is several methods to achieve that:
array = [1, 2]
array += [3, 4] # => [1, 2, 3, 4]
# push: put the element at the end of the array
array.push([5, 6]) # => [1, 2, 3, 4, [5, 6]]
array.push(*[7, 8]) # => [1, 2, 3, 4, [5, 6], 7, 8]
array << 9 # => [1, 2, 3, 4, [5, 6], 7, 8, 9]
# unshift: put the element at the beginning of the array:
array.unshift(0) #=> [0, 1, 2, 3, 4, [5, 6], 7, 8, 9]
Some links:
- Array in Ruby 1.9.3: http://ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/Array.html
- Array in Ruby 2.0.0: http://www.ruby-doc.org/core-2.0.0/Array.html
Solution 5 - Arrays
Use Array#insert can add an array to any position:
a = [1, 2, 3]
b = [4,5,6]
b.insert(0, *a)
=> [1, 2, 3, 4, 5, 6]
Solution 6 - Arrays
just use .flatten
for example if you have this array
array = [1,2,3,4,5,6]
and you do this
array.push([123,456,789])
array.push([["abc","def"],["ghi","jkl"]])
your string would look something like
array = [[1,2,3,4,5,6],[123,456,789],[["abc","def"],["ghi","jkl"]]]
all you need to do is
array.flatten!
and now your array would like this
array = [1,2,3,4,5,6,123,456,789,"abc","def","ghi","jkl"]
Solution 7 - Arrays
One more, for building up an array with items n-times you can use the splat (AKA asterisk, *
):
arr = [true] * 4 # => [true, true, true, true]
You can also use the splat for repeating multiple elements:
arr = [123,'abc'] * 3 # => [123,'abc',123,'abc',123,'abc']
Of course, you can use any array operators with that, such as +:
arr = [true] * 3 + [false] # => [true, true, true, false]
I use that in conjunction with #sample
to generate random weighted results:
arr.sample # => true 3 out of 4 times