The each_with_index method takes an enumerable collection yields one element at a time to the given block, along with an index number.
- View the objects used in these examples
- View these examples as a runnable ruby script on GitHub.
Number List
@numbers = [1, 0, 3, 2, 5, 4, 7, 6, 9, 8] # all numbers with index: @numbers.each_with_index{|number, i| puts "#{i}: #{number}"} # output # 0: 1 # 1: 0 # 2: 3 # 3: 2 # 4: 5 # 5: 4 # 6: 7 # 7: 6 # 8: 9 # 9: 8 # the even status for all numbers, with index: @numbers.each_with_index{|number, i| puts "#{i}: #{number.even?}"} # output # 0: false # 1: true # 2: false # 3: true # 4: false # 5: true # 6: false # 7: true # 8: false # 9: true
Pet Inventory
# leg counts for all pets, with index: @inventory.each_with_index{|pet, i| puts "#{i}: #{pet.legs}"} # output # 0: 4 # 1: 4 # 2: 0 # 3: 8 # 4: 6 # 5: 2 # 6: 0 # leg totals for each pet type, with index: @inventory.each_with_index{|pet, i| puts "#{i}: #{pet.legs * pet.quantity}"} # output # 0: 400 # 1: 200 # 2: 0 # 3: 8 # 4: 60000 # 5: 4 # 6: 0
Pokey Things
@pokey_things.seek(0) # letter counts for all pokey things, with index: @pokey_things.each_with_index{|thing, i| puts "#{i}: #{thing.chomp.size}"} # output # 0: 6 # 1: 4 # 2: 5 # 3: 41 @pokey_things.seek(0) # all pokey things, capitalized, with index: @pokey_things.each_with_index{|thing, i| puts "#{i}: #{thing.chomp.capitalize}"} # output # 0: Cactus # 1: Pole # 2: Knife # 3: Cactus holding poles with knives attached
Heroku Log File
# request methods for all heroku requests, with index: @requests.each_with_index{|request, i| puts "#{i}: #{request.method}"} # output # 0: GET # 1: GET # 2: GET # 3: GET # 4: GET # 5: GET # 6: GET # 7: GET # 8: GET # 9: GET # 10: GET # 11: GET # 12: GET # 13: GET # 14: GET # 15: GET # 16: GET # 17: GET # 18: GET # 19: GET # 20: GET # 21: POST # 22: GET # 23: GET # 24: GET # 25: GET # 26: GET # 27: GET # 28: GET # 29: GET # 30: GET # total response times for all heroku requests, with index: @requests.each_with_index{|request, i| puts "#{i}: #{request.connect + request.service}"} # output # 0: 1459 # 1: 1642 # 2: 17 # 3: 2 # 4: 1 # 5: 1 # 6: 3 # 7: 0 # 8: 1008 # 9: 1 # 10: 2 # 11: 1015 # 12: 994 # 13: 1371 # 14: 18 # 15: 10 # 16: 2 # 17: 17 # 18: 2 # 19: 2 # 20: 1 # 21: 60 # 22: 3 # 23: 912 # 24: 1 # 25: 5 # 26: 697 # 27: 3 # 28: 863 # 29: 1318 # 30: 696