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

Snippets has posted 5883 posts at DZone. View Full User Profile

Iterating Over A List

05.31.2005
| 11783 views |
  • submit to reddit
        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 use each_with_index instead.

Michael Campbell replied on Sat, 2006/09/09 - 5:48pm

<%= %w(evenline oddline)[my_folder.index(i) % 2] %>

Snippets Manager replied on Mon, 2012/05/07 - 2:12pm

<%= (my_folder.index(i) % 2 == 0) ? 'evenline' : 'oddline' %>

Snippets Manager replied on Mon, 2012/05/07 - 2:12pm

A clunky alternative: <% if my_folder.index(i) % 2 == 0 @linestyle = 'evenline' else @linestyle = 'oddline' end %>