There is each_pair method allows getting pairs of hash on every loop iteration:
{ 1 => "a", 2 => "b" }.each_pair do |key, value|
# do something with #{key} and #{value}
end
How can index of current array element could be known on every loop iteration?
array.each do |element|
# what is element index in array?
end
There is a boring solution using some incrementing iterator. But that iterator
should be assigned before the loop and should be manually incremented on every
iteration. It’s obviously boring.
It will be great if there is a some way to zip some array with 1.. array and
get array of tuples like ["b", "d", "e"] → [(1,"b"), (2,"d"), (3,"e")] and| |` statement.
than pattern matched each element of the pair in
So, finally, what I am looking for is some function f, that:
f(["a"]) do |index, element|
# index == 1, element == "a"
end
You can loop over an array and get the current index by using Enumerable::each_with_index