Is it possible to loop through a result set in the order as given but only print out the index in reverse? Example:
items = ["a", "b", "c"]
items.each_with_index do |value, index|
puts index.to_s + ": " + value
end
Gives:
0: a
1: b
2: c
Is there a way to reverse only the index so that the output is:
2: a
1: b
0: c
I’m not sure what you want to achieve, but chaining enumerators with reverse_each could be useful:
items.reverse_each.each_with_index do |value, index|
puts index.to_s + ": " + value
end
produces:
0: c
1: b
2: a
Add another reverse_each to get exactly the result you ask for:
items.reverse_each.each_with_index.reverse_each do |value, index|
puts index.to_s + ": " + value
end
produces:
2: a
1: b
0: c
Using Enumerable#zip:
>> items = %w{a b c}
>> (0...items.size).reverse_each.zip(items) do |index, value|
?> puts "#{index}: #{value}"
>> end
2: a
1: b
0: c
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With