How do I iterate through an array with an index?
You’re probably familiar with iterating through an array or hash: Normally, you’d iterate through it with something like this:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
company_names = ["Tekfly", "Yabox", "Vinder", "Skiptube", "Fivespan"] | |
company_names.each do |company_name| | |
puts "#{company_name}" | |
end |
Which would generate this output:
Tekfly
Yabox
Vinder
Skiptube
Fivespan
But what if we wanted to iterate through with an index (maybe for use in css or JavaScript identifiers in our view template)? That’s where each_with_index
comes in.
Swap out each
with each_with_index
, put in a second argument for the index and you’re good to go!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
company_names = ["Tekfly", "Yabox", "Vinder", "Skiptube", "Fivespan"] | |
company_names.each_with_index do |company_name, index| | |
puts "#{company_name} has index #{index}" | |
end |
This creates output like this:
Tekfly has index 0
Yabox has index 1
Vinder has index 2
Skiptube has index 3
Fivespan has index 4
For more information on each_with_index
, check out the RubyDoc