Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to iterate over multiple arrays?

Tags:

arrays

loops

ruby

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.

like image 484
m.silenus Avatar asked Jan 27 '11 13:01

m.silenus


People also ask

How do you traverse two arrays simultaneously?

for the first value in array1 you need to loop through the values in array2 (value1, value2, value3…) for the second value in array1 you need to loop through the values in array2 (value1, value2 value3…) for the third value in array1 you need to loop through the values in array2 (value1, value2 value3…)

How do I iterate over two arrays in JavaScript?

To use forEach to loop through two arrays at the same time in JavaScript, we can use the index parameter of the forEach callback to get the element with the same index from the 2nd array. const n = [1, 2, 3, 5, 7, 8, 9, 11, 12, 13]; const m = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; n.

How do you iterate two arrays in Python?

Use the izip() Function to Iterate Over Two Lists in Python It iterates over the lists until the smallest of them gets exhausted. It then zips or maps the elements of both lists together and returns an iterator object. It returns the elements of both lists mapped together according to their index.

Is it possible to iterate over arrays?

Iterating over an arrayYou can iterate over an array using for loop or forEach loop. Using the for loop − Instead on printing element by element, you can iterate the index using for loop starting from 0 to length of the array (ArrayName. length) and access elements at each index.


1 Answers

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)
like image 159
Dylan Markow Avatar answered Nov 03 '22 19:11

Dylan Markow