ruby

Ruby Hash iteration with index

12/12/2015

Ruby Hash (and Array) includes the Enumerable module (mixin), which provides a lot of neat, but also slightly hidden in the documentation, methods. This means that despite the poor advertising you can iterate not only each key and value, but the index as well:

months = { January: 31, February: 28, March: 31, April: 30, May: 31, June: 30, July: 31, August: 31, September: 30, October: 31, November: 30, December: 31 }

months.each_with_index do |(key, val), i|
	puts "#{i}: #{key} has #{val} days"
end