3

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
2
  • Presume you mean items = ["a", "b", "c"] (array [], not hash {}) Commented Jan 10, 2014 at 3:04
  • Yes, sorry fixed the question. Commented Jan 10, 2014 at 3:05

4 Answers 4

4

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
Sign up to request clarification or add additional context in comments.

Comments

3

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

2 Comments

Thanks. I was wondering if there's a more ruby way to achieve this as well (maybe a built in function).
@Hopstream, I added an alternative that use Enumerable#zip.
0

Simply substract the index from items length, and an additional - 1 to match indices:

items.each_with_index { |val, index| puts (items.length - index - 1).to_s + ": " + val }

Comments

0
offset = items.length - 1
items.each_with_index { |value, i| puts "#{offset - i}: #{value}" }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.