Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge and interleave two arrays in Ruby

Tags:

arrays

ruby

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?

like image 221
Chris Ledet Avatar asked Sep 05 '11 21:09

Chris Ledet


People also ask

How do I merge two arrays in Ruby?

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).

How do you add an array to an 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. Note: This method permanently changes the original array.

How do you merge arrays?

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.

What is .first in Ruby?

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.


2 Answers

You can do that with:

a.zip(s).flatten.compact 
like image 132
DigitalRoss Avatar answered Sep 18 '22 17:09

DigitalRoss


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.

like image 42
Michael Stalker Avatar answered Sep 17 '22 17:09

Michael Stalker