在 Ruby 中迭代多个数组的最佳(美观且高效)方法是什么?
假设我们有一个数组:
a=[x,y,z]
b=['a','b','c']
我想要这个:
x a
y b
z c
Thanks.
另一种方法是使用each_with_index
。快速基准测试表明,这比使用 zip 稍快。
a.each_with_index do |item, index|
puts item, b[index]
end
基准:
a = ["x","y","z"]
b = ["a","b","c"]
Benchmark.bm do |bm|
bm.report("ewi") do
10_000_000.times do
a.each_with_index do |item, index|
item_a = item
item_b = b[index]
end
end
end
bm.report("zip") do
10_000_000.times do
a.zip(b) do |items|
item_a = items[0]
item_b = items[1]
end
end
end
end
Results:
user system total real
ewi 7.890000 0.000000 7.890000 ( 7.887574)
zip 10.920000 0.010000 10.930000 ( 10.918568)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)