Topic: For loops

I know that ruby has for loops that are different to the traditional for loops in other languages, but I need to iterate over an array passed as a parameter in rails, and as a result I need to know the current loop it's going over.

In java i could just do this:

for (int i=0;i<something.length;i++) {

and i would be the current pass. How do I get the value of i in ruby?

I tried the following:

   1.       <% for i in 0..@actions.length.times %>  
   2.         <tr><td><%= action %></td>
   3.         <td><%= text_field('friendly_name', :size => '15', :id => i+"_0"?)%></td>
   4.         <%= hidden_field_tag('ctrl', controller, :id => i+"_1") %>
   5.         <%= hidden_field_tag('actn', action, :id => i+"_2") %>
   6.         <td><%= check_box_tag('method_list[]', :id => i+"_3") %></td>
   7.         </tr>
   8.       <% end -%>

Unfortunately it didn't work, claims that no block is given. I know that this is rails code but I figured a question about for loops belongs here.


Re: For loops

One way to do it:

0.upto(@actions.length) do |n|
  #do something with n
end - Brewery and Brewpub management powered by RoR

Re: For loops

works a charm thanks.
I'm guessing that the |n| is the block then?


Re: For loops

Not exactly.  n is your iterator.  It can also be written like this:

0.upto(@actions.length) { |n| <this_is_your_block> } - Brewery and Brewpub management powered by RoR

Re: For loops

Hey this is freakin cool!