Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby reverse only index but keep values in place?

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
like image 781
Hopstream Avatar asked Nov 29 '25 10:11

Hopstream


2 Answers

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
like image 110
matt Avatar answered Nov 30 '25 23:11

matt


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
like image 24
falsetru Avatar answered Dec 01 '25 00:12

falsetru