views:

251

answers:

2

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

+9  A: 

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 %>
zaius
Ah nice, I guess the second option is what I was looking for.
Zepplock
Also is there a way to assign an initial value to "n"?
Zepplock
Assign an initial value and then increment by 1 each time? The index isn't a counter - it's an index. If you want to increase it by a fixed offset, just add it when you print: <%= n + 5 %>
zaius
A: 

Um.

n = @items.size
glenn mcdonald
No, @items.size is a constant (within a loop scope)
Zepplock
Ah, I assume you mean that you're doing something [i]else[/i] with it in the loop, not shown in your example?
glenn mcdonald