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:

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 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](http://apidock.com/ruby/Enumerator/each_with_index)

Leave a Reply

Your email address will not be published. Required fields are marked *