I have the following code:
a = [\"Cat\", \"Dog\", \"Mouse\"]
s = [\"and\", \"&\"]
I want to merge the array s
into array <
Interleave 2D array of any size
arr = [["Cat", "Dog", "Mouse"],
["and", "&"],
["hello", "there", "you", "boo", "zoo"]]
max_count = arr.map(&:count).max
max_count.times.map{|i| arr.map{|a| a[i]}}.flatten.compact
#=> ["Cat", "and", "hello", "Dog", "&", "there", "Mouse", "you", "boo", "zoo"]
s.inject(a, :<<)
s #=> ["and", "&"]
a #=> ["Cat", "Dog", "Mouse", "and", "&"]
It doesn't give you the order you asked for, but it's a nice way of merging two arrays by appending to the one.
It's not exactly elegant, but it works for arrays of any size:
>> a.map.with_index { |x, i| [x, i == a.size - 2 ? s.last : s.first] }.flatten[0..-2]
#=> ["Cat", "and", "Dog", "&", "Mouse"]
Here's a solution that allows interleaving multiple arrays of different sizes (general solution):
arr = [["Cat", "Dog", "Mouse", "boo", "zoo"],
["and", "&"],
["hello", "there", "you"]]
first, *rest = *arr; first.zip(*rest).flatten.compact
=> ["Cat", "and", "hello", "Dog", "&", "there", "Mouse", "you", "boo", "zoo"]
To handle the situation where both a
& s
are not of the same size:
a.zip(s).flatten.compact | s
.compact
will remove nil
when a
is larger than s
| s
will add the remaining items from s
when a
is smaller than s