Nick Ginanto
Nick Ginanto

Reputation: 32160

Zipping arrays with every n-th element

Is there a way to use zip in such a way that 2 arrays will be zipped with spaces between n-elements such as:

a = [1,2,3,4,5,6,7,8,9,10]
b = ["x","y","z"]
n = 3

the result will be

res = [[1,"x"],2,3,[4,"y"],5,6,[7,"z"],8,9,10] # note that 10 is alone and b is not cycled

Upvotes: 2

Views: 98

Answers (3)

steenslag
steenslag

Reputation: 80075

Iterating over b is a possibility:

# Note this destroys array a;use a dup it if it is needed elsewhere
res = b.flat_map{|el| [[el].unshift(a.shift), *a.shift(n-1)] }.concat(a) 

Upvotes: 0

pguardiario
pguardiario

Reputation: 55002

How about:

a.map.with_index{|x, i| i%n < 1 && b.size > i/n ? [x, b[i/n]] : x}
#=> [[1, "x"], 2, 3, [4, "y"], 5, 6, [7, "z"], 8, 9, 10]

Upvotes: 0

tokland
tokland

Reputation: 67900

I'd write:

res = a.each_slice(n).zip(b).flat_map do |xs, y| 
  y ? [[xs.first, y], *xs.drop(1)] : xs
end
#=> [[1, "x"], 2, 3, [4, "y"], 5, 6, [7, "z"], 8, 9, 10]

Upvotes: 6

Related Questions