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
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 %>
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 %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With