tags:

views:

203

answers:

2

I'm probably missing something obvious, but is there a way to access the index/count of the iteration inside a hash each loop?

hash = {'three' => 'one', 'four' => 'two', 'one' => 'three'}
hash.each { |key, value| 
    # any way to know which iteration this is
    #   (without having to create a count variable)?
}
+3  A: 

You could iterate over the keys, and get the values out manually:

hash.keys.each_with_index do |key, index|
   value = hash[key]
   print "key: #{key}, value: #{value}, index: #{index}\n"
   # use key, value and index as desired
end

EDIT: per rampion's comment, I also just learned you can get both the key and value as a tuple if you iterate over hash:

hash.each_with_index do |(key, value), index|
   print "key: #{key}, value: #{value}, index: #{index}\n"
   # use key, value and index as desired
end
Kaleb Brasee
+4  A: 

If you like to know Index of each iteration you could use .each_with_index

S.Mark
specifically: `hash.each_with_index { |(key,value),index| ... }`
rampion
the parens are necessary b/c `hash.each` gives each key-value pair in an `Array`. The parens do the same thing as `(key,value) = arr`, putting the first value (the key) into `key`, and the second into `value`.
rampion
Thanks for follow up rampion
S.Mark
Thanks @S.Mark, @rampion, that worked. I didn't see `each_with_index` listed in the RDoc for Hash: http://ruby-doc.org/core/classes/Hash.html. Now I see that it's a member of Enumerable. But too bad that RDoc can't cross reference `each_with_index` from Hash.html.
Dave Paroulek
@Dave_Paroulek I've often wished the same. I've found checking the parent modules manually a necessary step when using vi to check a classes's methods. Often I just skip to `irb`, and use `ClassName#instance_methods` to make sure there's nothing I missed.
rampion
Thx, @rampion, `ClassName#instance_methods` has been very helpful
Dave Paroulek