Reputation: 29135
Is this the DRYest way to do it in ruby?
<% for item in @items %>
<%= n = n + 1 rescue n = 1 %>
<% end %>
which initializes "n" to '1" and increments it as the loop progresses (and prints it out) since this is in one my app's views
Upvotes: 6
Views: 6282
Reputation: 7012
You could also rely on ruby's nil coercion to an integer which results in zero.
<% for item in @items %>
<%= n = n.to_i + 1 %>
<% end %>
Upvotes: 6
Reputation: 6409
You can use a ternary operator:
<% for item in @items %>
<%= n = n ? n+1 : 1 %>
<% end %>
But, depending on what you're trying to do, I'm guessing an each_with_index would be more appropriate
<% @items.each_with_index do |item, n| %>
<%= n %>
<% end %>
Upvotes: 16