Ruby中多个数组的并行迭代操作

昨天蛋疼了 写了个Ruby的并行迭代

[code="ruby"]
a=[1,2,3] b=[4,5,6]

def both(*enumerables)
enumerators = enumerables.map { |e| e.to_enum }
loop { yield enumerators.map { |e| e.next } }
end

both(a,b) { |i| print(i) }
[/code]

输出结果
[code="ruby"][1,4] [2,5] [3,6][/code]

我想要用这个both迭代器实现两个数组中元素逐个操作,就是类似
[code="ruby"]
i=0
while(i<a.length) { puts(a[i]*b[i])}
[/code]
这样的操作,请问能实现吗?

你写的并行迭代是没有问题的,在向yield中传入的代码块中进行两个数组的操作就好了。稍作改动如下 [code="Ruby"] both(a,b) { |i| puts i[0]*i[1]}[/code] 这样就得到结果 4,10,8

a=[1,2,3]; b=[4,5,6]
a.size.times{|i| puts a[i] * b[i] }