I have the following code:
a = ["Cat", "Dog", "Mouse"] s = ["and", "&"]
I want to merge the array s
into array a
which would give me:
["Cat", "and", "Dog", "&", "Mouse"]
Looking through the Ruby Array and Enumerable docs, I don't see such a method that will accomplish this.
Is there a way I can do this without iterating through each array?
This can be done in a few ways in Ruby. The first is the plus operator. This will append one array to the end of another, creating a third array with the elements of both. Alternatively, use the concat method (the + operator and concat method are functionally equivalent).
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. Note: This method permanently changes the original array.
To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.
The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Syntax: range1.first(X) Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.
You can do that with:
a.zip(s).flatten.compact
This won't give a result array in the order Chris asked for, but if the order of the resulting array doesn't matter, you can just use a |= b
. If you don't want to mutate a
, you can write a | b
and assign the result to a variable.
See the set union documentation for the Array class at http://www.ruby-doc.org/core/classes/Array.html#M000275.
This answer assumes that you don't want duplicate array elements. If you want to allow duplicate elements in your final array, a += b
should do the trick. Again, if you don't want to mutate a
, use a + b
and assign the result to a variable.
In response to some of the comments on this page, these two solutions will work with arrays of any size.
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