Victor
Victor

Reputation: 13368

Rails each_with_index descend order in index

Using Rails 3.2 and Ruby 1.9. When we code @objects.each_with_index do |object, i|, i usually starts with 0, 1, 2. etc.

Let's say we have @objects = [A, B, C, D, E], and the output is:

<% @objects.each_with_index do |object, i| %>
  <%= i %> - <%= object %><br>
<% end %>

# output
0 - A
1 - B
2 - C

I wanna have this instead:

# output
2 - A
1 - B
0 - C

How to do this?

Upvotes: 2

Views: 884

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118261

How is this?

a = [:a,:b,:c]
a.each.with_index(-a.length+1) {|e,i| print -i,"  ",e,"\n"}

output:

2  a
1  b
0  c

Your one could be something like that:

<% @objects.each.with_index([email protected]+1) do |object, i| %>
  <%= -i %> - <%= object %><br>
<% end %>

Upvotes: 1

Ben
Ben

Reputation: 13615

<%= @objects.length - 1 - i %> - <%= object %><br>

this will substract the index of the length of the array, giving the desired output.

You have to always substract one from the length since a array with length 3 has indexes 0, 1, 2

Upvotes: 8

Related Questions