I want to start any where in an array (for example) the last two elements in arr and access the elements as well as their respective indexes 1,2.
Is there a more elegant way to do this?
Without using a the standard method (below) with an index variable i and while.
arr = [82,217,170]
i = 3
while i < arr.length
puts "#{arr[i]}" + " " + "#{i}"
end
Other loop methods can begin at a specific element but return a new array.
I cannot print the elements' respective indexes because its now referring to the new array.
arr = [82,217,170]
arr.drop(1).each_with_index do |item,index|
puts "#{item}" + " " + "#{index}"
end
arr[1..2].each_with_index do |item,index|
puts "#{item}" + " " + "#{index}"
end
Output:
217 0 <== should be 1
170 1 <== should be 2
217 0 <== should be 1
170 1 <== should be 2
Reason for question and Uses:
This would be useful if you want to have nested loops in a function that already has a lot of code. You don't have to instantiate multiple index variables outside of each loop.