Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Michael Koziarski http://www.koziarski.net/

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Iterating over a list

One of the common things you want to do with a table in a web application is use different classes so the rows have different styles. i.e alternate between light and dark backgrounds.

Arry#cycle is a method to enable that.

   1  
   2  class Array
   3    def cycle(values)
   4      self.each_with_index do |o, i| 
   5        yield(o, values[i % values.length])
   6      end
   7    end
   8  end


You can use it like this:

   1  
   2  <% @something.cycle(["oddRow", "evenRow"]) do |obj, cssClass| %>
   3    <tr class="<%= cssClass %>">
   4      <td><%= obj.something %></td>
   5      <td><%= obj.something_else %></td>
   6    </tr>
   7  <% end %>
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS