3

I have been trying to change my loop to decrement rather than increment. Nothing I have tried is working, please can someone help me.

<% @orders.each do |order| %>
   #code
<% end %>

Thanks

1
  • 2
    The problem is you're not understanding what each does. It traverses the contents of your @orders array, from the first element to the last. To walk that list backwards you have to reverse the list somehow. The Array documentation covers that nicely. Commented Jul 16, 2013 at 18:39

2 Answers 2

13

Array#reverse_each

Same as Array#each, but traverses self in reverse order.

try the below :

<% @orders.reverse_each do |order| %>
   #code
<% end %>
Sign up to request clarification or add additional context in comments.

1 Comment

This is even better than @orders.reverse.each as well, in case someone considered that. At least on MRI, reverse_each is implemented as a loop that counts from the end of the array to the beginning, while reverse.each creates a new array and then loops over that (so, reverse_each is roughly O(n), while reverse.each is roughly O(2n) (disclaimer: I don't actually know big O notation, so this may be completely wrong)).
3

You might want to consider

@orders = Order.where(whatever: 'something').order('created_at DESC')

Above, we sorted the @orders by the created_at field. You could sort using whichever field you like. Then you can iterate normally

<% @orders.each do |order| %>
  yay!
<% end %>

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.