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.
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…)
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With