Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

I tried:

somearray = ["some", "thing"] anotherarray = ["another", "thing"] somearray.push(anotherarray.flatten!) 

I expected

["some", "thing", "another", "thing"] 

but got

["some", "thing", nil] 
like image 928
ncvncvn Avatar asked Nov 26 '09 04:11

ncvncvn


People also ask

How do you append an array to another array in Ruby?

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.

How do you create a nested array in Ruby?

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.

Can an array be an element of another array?

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.

How do you add an array of contents in Ruby?

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.


1 Answers

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 
like image 76
pilcrow Avatar answered Sep 27 '22 20:09

pilcrow