Make Love not War

Counter one liner in Ruby

July 19th 2009

Many times I have to make a counter that starts with 1 and monotonically incremented by 1 in Rails view. The typical example is when showing a list of things like:

7.1
7.2
7.3
....

The nice trick is to make it in 1 line:

<li>7.<%= n = n + 1 rescue n = 1 %></li>

instead of initializing “n” before the loop (which requires extra line of code).

blog comments powered by Disqus