group_by Month

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.
 
学习如何使用group_by方法将一个数组按照你的意愿分组。这一节我会将任务按照月来分组然后适当的进行排列。
---
029 按月分组 group_by Month_by
先来了解一下group_by方法:
 
>>script/console
>>a=(1..20).to_a
>>[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
>>a.group_by {|num| num/5}
=>{0=>[1,2,3,4],1=>[5,6,7,8],2=>[10,11,12,13,14],3=>[15,16,17,18,19],4=>[20]}
--回来原先那个例子中:
 
def index
    @task_months=@tasks.group_by {|t| t.due_at.beginning_of_month}
end
 
在view中循环这个变量
 
<% @task_months.each do |month,tasks|%>
    <h2><%= month.strftime('%B')%></h2>
    <% for task in tasks%>
      <%=task.name%>
    due on<%= task.due_at.to_date.to_s(:long)%>
  <%end%>
<%end%>
 
修改之后显示就是这样的了:
 
029 按月分组 group_by Month_railscasts_02
看到,虽然这是按着月这样排了,但是发现April,June,May不是按顺序的。
所以:
<% @task_months.keys.each do |month|%>
    <h2><%= month.strftime('%B')%></h2>
    <% for task in @task_months[month]%>
      <%=task.name%>
    due on<%= task.due_at.to_date.to_s(:long)%>
  <%end%>
<%end%>
 
先对hash的key循环,然后内部对value循环。