How to alternate arrays of different lengths in Ruby

If I want to alternate a set of arrays in Ruby, and each array has the same length, we could do it like:

a.zip(b).zip(c).flatten 

However, how to solve this problem if arrays can be of different sizes?

We could do something like:

 def interleave(*args) raise 'No arrays to interleave' if args.empty? max_length = args.inject(0) { |length, elem| length = [length, elem.length].max } output = Array.new for i in 0...max_length args.each { |elem| output << elem[i] if i < elem.length } end return output end 

But is there a better way to "Ruby", possibly using zip or transpose, or some?

+7
arrays ruby
source share
3 answers

If the original arrays do not have nil in them, you only need to expand the first array with nil s, zip will automatically place the rest with nil . It also means that you can use compact to clean up extra records, which we hope will be more efficient than explicit contours.

 def interleave(a,*args) max_length = args.map(&:size).max padding = [nil]*[max_length-a.size, 0].max (a+padding).zip(*args).flatten.compact end 

Here is a slightly more complicated version that works if arrays contain nil

 def interleave(*args) max_length = args.map(&:size).max pad = Object.new() args = args.map{|a| a.dup.fill(pad,(a.size...max_length))} ([pad]*max_length).zip(*args).flatten-[pad] end 
+7
source share

Here is a simpler approach. It uses the transfer order of arrays in zip :

 def interleave(a, b) if a.length >= b.length a.zip(b) else b.zip(a).map(&:reverse) end.flatten.compact end interleave([21, 22], [31, 32, 33]) # => [21, 31, 22, 32, 33] interleave([31, 32, 33], [21, 22]) # => [31, 21, 32, 22, 33] interleave([], [21, 22]) # => [21, 22] interleave([], []) # => [] 

Be warned: this removes all nil 's:

 interleave([11], [41, 42, 43, 44, nil]) # => [11, 41, 42, 43, 44] 
+6
source share

Your implementation looks good to me. You can achieve this by using #zip, filling the arrays with some garbage, button them, then flatten and remove the garbage. But this is too confusing IMO. What you have here is pure and self-evident, it just needs to be rubified.

Change Fixed booboo.

 def interleave(*args) raise 'No arrays to interleave' if args.empty? max_length = args.map(&:size).max output = [] max_length.times do |i| args.each do |elem| output << elem[i] if i < elem.length end end output end a = [*1..5] # => [1, 2, 3, 4, 5] b = [*6..15] # => [6, 7, 8, 9, 10, 11, 12, 13, 14, 15] c = [*16..18] # => [16, 17, 18] interleave(a,b,c) # => [1, 6, 16, 2, 7, 17, 3, 8, 18, 4, 9, 5, 10, 11, 12, 13, 14, 15] 

Edit : for fun

 def interleave(*args) raise 'No arrays to interleave' if args.empty? max_length = args.map(&:size).max # assumes no values coming in will contain nil. using dup because fill mutates args.map{|e| e.dup.fill(nil, e.size...max_length)}.inject(:zip).flatten.compact end interleave(a,b,c) # => [1, 6, 16, 2, 7, 17, 3, 8, 18, 4, 9, 5, 10, 11, 12, 13, 14, 15] 
+5
source share

All Articles