DZone 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
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 %>