有没有一种方法可以使用 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
最佳答案
我会写:
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]
关于ruby - 用每个第 n 个元素压缩数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14085741/