Zepplock
Zepplock

Reputation: 29135

initializing and incrementing a variable in one line of code

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

Answers (3)

dnatoli
dnatoli

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

glenn mcdonald
glenn mcdonald

Reputation: 15478

Um.

n = @items.size

Upvotes: 0

zaius
zaius

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

Related Questions