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






Comments
Snippets Manager replied on Mon, 2006/02/20 - 6:31pm
index(x)is O(n). Probably better do just useeach_with_indexinstead.Michael Campbell replied on Sat, 2006/09/09 - 5:48pm
Snippets Manager replied on Mon, 2012/05/07 - 2:12pm
Snippets Manager replied on Mon, 2012/05/07 - 2:12pm
<% if my_folder.index(i) % 2 == 0 @linestyle = 'evenline' else @linestyle = 'oddline' end %>