029 按月分组 group_by Month

简介:

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方法将一个数组按照你的意愿分组。这一节我会将任务按照月来分组然后适当的进行排列。
---
先来了解一下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%>
 
修改之后显示就是这样的了:
 
看到,虽然这是按着月这样排了,但是发现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循环。
 




本文转自 fsjoy1983 51CTO博客,原文链接:http://blog.51cto.com/fsjoy/131943,如需转载请自行联系原作者
目录
相关文章
|
6月前
|
开发框架 .NET 编译器
C#-Group By 的使用
group by 是linq中的分组功能,能通过给定的字段对数据集进行分组,得到分组后的结果。
127 0
|
10月前
|
SQL 关系型数据库 MySQL
GROUP BY和ORDER BY的区别
GROUP BY和ORDER BY的区别
239 0
|
11月前
|
SQL 关系型数据库 MySQL
only_full_group_by问题而引发的对group by的深入思考
only_full_group_by问题而引发的对group by的深入思考
104 0
group by+group_concat解决的小问题
group by+group_concat解决的小问题
77 0
|
SQL
ORDER BY && GROUP BY
ORDER BY && GROUP BY
61 0
ORDER BY && GROUP BY
group by
group by
66 0
GROUP BY 一个以上的列
GROUP BY 一个以上的列
71 1
|
SQL
十、GROUP BY 和 HAVING 的使用
十、GROUP BY 和 HAVING 的使用
243 0
|
SQL 关系型数据库 数据挖掘
你真的懂使用Group by?
你真的懂使用Group by?
463 0
你真的懂使用Group by?
函数的理解 group by order by理解
函数的分类 单行函数 对每一行记录都有作用 对每一行记录都能返回一个结果 例子lower(ename) 对每一个记录的ename字段都返回一个结果 多行函数 对一组记录返回一个结果 聚合函数就是多行函数 例子l...
1136 0