Twitter Updates

Tuesday 17 March 2009

Ruby loops

Incrementing loops in ruby is easy (eamples in ERB)
<% (0...4).each do |i| %>

<%=i%><% end %>
This will output
0
1
2
3

NB: the '...' mean one less than the number. '..' would out put 0-4

Decrementing loops are a little harder, as low..high numbering is required for the previous format.
<% (4-1).downto(0) do |i| %>

<%=i%><% end %>
This will output
3
2
1
0

NOTE [29/04/2009]
Because these loops are generated using an iterator you can not just set i to the value you want next, ie to jump a value or increment/decrement in 2's. for this a for/while loop must be used.

<% i=0 %>

<% while (i<8) %>
<%=i%>
<% i=i+2
end %>

No comments: