6

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

3 Answers 3

16

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 %>
Sign up to request clarification or add additional context in comments.

3 Comments

Ah nice, I guess the second option is what I was looking for.
Also is there a way to assign an initial value to "n"?
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 %>
6

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 %>

Comments

0

Um.

n = @items.size

2 Comments

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

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.