Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get number of times in loop over Hash object

I have an object of type Hash that I want to loop over via hash.each do |key, value|. I would like to get the number of times I've been through the loop starting at 1.

Is there a method similar to each that provides this (while still providing the hash key/value data), or do I need to create another counter variable to increment within the loop?

like image 573
Matt Huggins Avatar asked Dec 22 '22 04:12

Matt Huggins


1 Answers

Use each_with_index instead of each. Note: the index does start at 0:

hash.each_with_index do |(key, value), index|
like image 166
Marc-André Lafortune Avatar answered Jan 04 '23 18:01

Marc-André Lafortune