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]]
.pusharr = [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]
Using += operator:
arr = [1]
arr += [2, 3]
arr
# => [1, 2, 3]
arr.You can do also as below using Array#concat:
arr = [1]
arr.concat([2, 3]) # => [1, 2, 3]
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:
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]
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"]
flatten is not the preferred way to do this. Understanding how arrays are concatenated shows that using + or += avoids the need to use flatten at all. flatten is for those times when we get arrays that we didn't generate, or were too lazy to build correctly.flatten over an array of arrays built using push than using += for every concatenation. You'll get more garbage and more copying with the latter. I'd also expect O(n^2) time from the latter, and O(n) from the former.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
arr.push *another_arrwill add theanother_arras flattened values (will not add an array but each value)