Array eachwithindex
📝 RubyIterate 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
I once spent two hours debugging a race condition because I used
for...inon an array instead offorEachwith the index parameter. The indices came back as strings and broke my comparison logic. Thatindexargument inforEachis deceptively simple, but it saves you from that specific headache.