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.

class Array
  def cycle(values)
    self.each_with_index do |o, i| 
      yield(o, values[i % values.length])
    end
  end
end


You can use it like this:

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