我有一个(ar)类PressClipping由标题和日期字段组成。红宝石组按月份和年份
我必须这样显示出来:
2011年2月
TITLE1
标题2
...
2011年1月
...
什么是执行最简单的方法分组?
我有一个(ar)类PressClipping由标题和日期字段组成。红宝石组按月份和年份
我必须这样显示出来:
2011年2月
TITLE1
标题2
...
2011年1月
...
什么是执行最简单的方法分组?
这里是展示如何使用Enumerable#group_by
迭代一些Haml的输出:
- @clippings_by_date.group_by{|c| c.date.strftime "%Y %b" }.each do |date_str,cs|
%h2.date= date_str
%ul.clippings
- cs.each do |clipping|
%li <a href="...">#{clipping.title}</a>
这给你一个散列结果,其中每个键是格式化的日期字符串,每个值是剪报那天的数组。这假设Ruby 1.9,其中哈希保存并迭代放置顺序。如果你是在1.8.x的,而不是你需要做的是这样:
- last_year_month = nil
- @clippings_by_date.each do |clipping|
- year_month = [ clipping.date.year, clipping.date.month ]
- if year_month != last_year_month
- last_year_month = year_month
%h2.date= clipping.date.strftime '%Y %b'
%p.clipping <a href="...>#{clipping.title}</a>
我想你可以拿1.8像这样下利用group_by
(只使用纯Ruby现在明白了吧):
by_yearmonth = @clippings_by_date.group_by{ |c| [c.date.year,c.date.month] }
by_yearmonth.keys.sort.each do |yearmonth|
clippings_this_month = by_yearmonth[yearmonth]
# Generate the month string just once and output it
clippings_this_month.each do |clipping|
# Output the clipping
end
end
请用您的代码进行更新。 – 2011-05-07 01:54:46