somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray.push(anotherarray.flatten!)
I expected
["some","thing","another","thing"]
I expected
|
||||
You've got a workable idea, but the I'm doubtless forgetting some approaches, but you can concatenate:
or prepend/append:
or splice:
or append and flatten:
|
|||||||||||||||||||||
|
You can just use the
You can read all about the array class here: http://ruby-doc.org/core/classes/Array.html |
|||||||||||||||||||||
|
The cleanest approach is to use the Array#concat method; it will not create a new array (unlike Array#+ which will do the same thing but create a new array). Straight from the docs (http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-concat):
So
Array#concat will not flatten a multidimensional array if it is passed in as an argument. You'll need to handle that separately:
Lastly, you can use our corelib gem (https://github.com/corlewsolutions/corelib) which adds useful helpers to the Ruby core classes. In particular we have an Array#add_all method which will automatically flatten multidimensional arrays before executing the concat. |
|||||||||
|
Here are two ways, notice in this case that the first way returns a new array ( translates to somearray = somearray + anotherarray )
|
|||
|
Try this, it will combine your arrays removing duplicates
http://www.ruby-doc.org/core/classes/Array.html Further documentation look at "Set Union" |
|||||
|
Easy method tested with Ruby 2.3.0 :
|
|||
This way you get array1 elements first. You will get no duplicates. |
|||
|
|
|||
|
I find it easier to push or append arrays and then flatten them in place, like so:
|
|||
|
If the new data could be an array or a scalar, and you want to prevent the new data to be nested if it was an array, the splat operator is awesome! It returns a scalar for a scalar, and an unpacked list of arguments for an array.
|
|||
|
The question, essentially, is "how to concatenate arrays in Ruby". Naturally the answer is to use A natural extension to the question would be "how to perform row-wise concatenation of 2D arrays in Ruby". When I googled "ruby concatenate matrices", this SO question was the top result so I thought I would leave my answer to that (unasked but related) question here for posterity. In some applications you might want to "concatenate" two 2D arrays row-wise. Something like,
This is something like "augmenting" a matrix. For example, I used this technique to create a single adjacency matrix to represent a graph out of a bunch of smaller matrices. Without this technique I would have had to iterate over the components in a way that could have been error prone or frustrating to think about. I might have had to do an
|
|||
|
ri Array@flatten!
Why this question is getting so many votes? The doc is explicitArray#flatten!
Flattens self in place. Returns nil if no modifications were made (i.e., the array contains no subarrays.) – yeyo Jan 31 '16 at 15:39