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

Iterating over a list (See related posts)

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 on this post

brook posts on May 31, 2005 at 15:32
A clunky alternative:

<% if my_folder.index(i) % 2 == 0
@linestyle = 'evenline'
else
@linestyle = 'oddline'
end %>
technoweenie posts on May 31, 2005 at 17:34
<%= (my_folder.index(i) % 2 == 0) ? 'evenline' : 'oddline' %>
MC posts on Sep 09, 2006 at 17:51
<%= %w(evenline oddline)[my_folder.index(i) % 2] %>
Qerub posts on Apr 04, 2007 at 18:22
index(x)<code> is O(n). Probably better do just use <code>each_with_index
instead.

You need to create an account or log in to post comments to this site.


Click here to browse all 4861 code snippets

Related Posts