← Back to Gists

Array eachwithindex

📝 Ruby
pattycarter249
pattycarter249 · Level 3 ·

Iterate over an array while accessing both the element and its index in each iteration.

Ruby
array = ["apple", "banana", "cherry"]
array.eachwithindex do |fruit, index| puts "#{index}: #{fruit}"
end

Comments

-1
jeffrey_hendrix jeffrey_hendrix

I once spent two hours debugging a race condition because I used for...in on an array instead of forEach with the index parameter. The indices came back as strings and broke my comparison logic. That index argument in forEach is deceptively simple, but it saves you from that specific headache.