I tried:
somearray = ["some", "thing"] anotherarray = ["another", "thing"] somearray.push(anotherarray.flatten!)
I expected
["some", "thing", "another", "thing"]
but got
["some", "thing", nil]
In this case, you can use the concat() method in Ruby. concat() is used to join, combine, concatenate, or append arrays. The concat() method returns a new array with all of the elements of the arrays combined into one.
To add data to a nested array, we can use the same << , or shovel, method we use to add data to a one-dimensional array. To add an element to an array that is nested inside of another array, we first use the same bracket notation as above to dig down to the nested array, and then we can use the << on it.
An array is said to fit into another array if by arranging the elements of both arrays, there exists a solution such that the ith element of the first array is less than or equal to ith element of the second array.
Loop. The simplest and most common way to add elements to an array is to use a loop. We start by defining a variable to store the sum of values and initialize it to 0. Next, we iterate over each element in the array and add them to the sum variable.
You've got a workable idea, but the #flatten!
is in the wrong place -- it flattens its receiver, so you could use it to turn [1, 2, ['foo', 'bar']]
into [1,2,'foo','bar']
.
I'm doubtless forgetting some approaches, but you can concatenate:
a1.concat a2 a1 + a2 # creates a new array, as does a1 += a2
or prepend/append:
a1.push(*a2) # note the asterisk a2.unshift(*a1) # note the asterisk, and that a2 is the receiver
or splice:
a1[a1.length, 0] = a2 a1[a1.length..0] = a2 a1.insert(a1.length, *a2)
or append and flatten:
(a1 << a2).flatten! # a call to #flatten instead would return a new array
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