2011-05-07 104 views
1

我有一个(ar)类PressClipping由标题和日期字段组成。红宝石组按月份和年份

我必须这样显示出来:

2011年2月
TITLE1
标题2
...
2011年1月
...

什么是执行最简单的方法分组?

+0

请用您的代码进行更新。 – 2011-05-07 01:54:46

回答

5

这里是展示如何使用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 
+0

非常感谢,我不知道我可以将lambda传递给group_by子句。 – Jan 2011-05-07 12:50:42

+0

@Jan Heh,我刚刚改变了删除lambda的答案。但是,一般来说,任何采用块的方法都可以通过使用'my_method(arg1,arg2,...,argn,&mylambda)'来传入proc/lambda' – Phrogz 2011-05-07 13:11:02