7

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.

m.silenus
  • 492
  • 7
  • 15
  • possible duplicate of [What's the 'Ruby way' to iterate over two arrays at once](http://stackoverflow.com/questions/3580049/whats-the-ruby-way-to-iterate-over-two-arrays-at-once) – dee-see Sep 09 '14 at 21:05

5 Answers5

6

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)
Dylan Markow
  • 123,080
  • 26
  • 284
  • 201
4

The zip method on array objects:

a.zip b do |items|
    puts items[0], items[1]
end
kelloti
  • 8,705
  • 5
  • 46
  • 82
2
>> a=["x","y","z"]
=> ["x", "y", "z"]
>> b=["a","b","c"]
=> ["a", "b", "c"]
>> a.zip(b)
=> [["x", "a"], ["y", "b"], ["z", "c"]]
>>
kurumi
  • 25,121
  • 5
  • 44
  • 52
1

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
Rob O B
  • 11
  • 1
1

See What is a Ruby equivalent for Python's "zip" builtin?

Community
  • 1
  • 1
Björn Lindqvist
  • 19,221
  • 20
  • 87
  • 122