使用每个第n个元素压缩数组

时间:2012-12-29 20:41:51

标签: ruby arrays

有没有办法以这样的方式使用zip:2个数组将在n元素之间用空格压缩,例如:

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

结果将是

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

3 个答案:

答案 0 :(得分:6)

我写道:

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]

答案 1 :(得分:0)

怎么样:

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]

答案 2 :(得分:0)

迭代b是可能的:

# 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) 
相关问题