Reputation: 492
What's is the best (beauty and efficient in terms of performance) way to iterate over multiple arrays in Ruby? Let's say we have an arrays:
a=[x,y,z]
b=['a','b','c']
and I want this:
x a
y b
z c
Thanks.
Upvotes: 7
Views: 3625
Reputation: 11
I like to use transpose when iterating through multiple arrays using Ruby. Hope this helps.
bigarray = []
bigarray << array_1
bigarray << array_2
bigarray << array_3
variableName = bigarray.transpose
variableName.each do |item1,item2,item3|
# do stuff per item
# eg
puts "item1"
puts "item2"
puts "item3"
end
Upvotes: 1
Reputation: 124419
An alternative is using each_with_index
. A quick benchmark shows that this is slightly faster than using zip.
a.each_with_index do |item, index|
puts item, b[index]
end
Benchmark:
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)
Upvotes: 6
Reputation: 25599
>> a=["x","y","z"]
=> ["x", "y", "z"]
>> b=["a","b","c"]
=> ["a", "b", "c"]
>> a.zip(b)
=> [["x", "a"], ["y", "b"], ["z", "c"]]
>>
Upvotes: 2
Reputation: 8951
The zip
method on array objects:
a.zip b do |items|
puts items[0], items[1]
end
Upvotes: 4
Reputation: 20372
See What is a Ruby equivalent for Python's "zip" builtin?
Upvotes: 1