Learn how to use the very useful group_by method to group an array by anything you want! In this episode I group an array of tasks by month then sort it properly.
# tasks_controller.rb
def index
@tasks = Task.find(:all, :order => 'due_at, id', :limit => 50)
@task_months = @tasks.group_by { |t| t.due_at.beginning_of_month }
end
<!-- tasks/index.rhtml -->
<% @task_months.sort.each do |month, tasks| %>
<h2><%= month.strftime('%B') %></h2>
<% for task in tasks %>
<div class="task">
<strong><%= task.name %></strong>
due on <%= task.due_at.to_date.to_s(:long) %>
</div>
<% end %>
<% end %>