Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 933
Zepplock Avatar asked Jul 19 '09 19:07

Zepplock


2 Answers

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 %>
like image 114
zaius Avatar answered Oct 11 '22 13:10

zaius


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 %>
like image 38
dnatoli Avatar answered Oct 11 '22 13:10

dnatoli