我有一系列日期,例如
Fri Jan 28 10:13:19 UTC 2011
Thu Jan 27 16:57:59 UTC 2011
Thu Jan 27 16:41:21 UTC 2011
Wed Jan 26 09:20:48 UTC 2011
Mon Jan 24 16:19:48 UTC 2011
Fri Jan 21 11:45:34 UTC 2011
Fri Jan 21 11:42:19 UTC 2011
如何对它们进行分组,使得输出与每天的项目数一样为哈希值:
Friday 28 => 1
Thursday 27 => 2
Wednesday 26 => 1
Monday 24 => 1
Friday 21 => 2
答案 0 :(得分:1)
@things.group_by {|thing| thing.strftime "%A %d" }.each do |key, group|
puts "#{key} => #{group.size}"
end
%A
是完整的工作日名称,%d
是该月的某一天
我目前无法测试,但我认为它会起作用。
答案 1 :(得分:1)
s=a.inject(Hash.new(0)) do |h,y|
z=y.split
h[ z[0]+z[2] ]+=1
h
end
答案 2 :(得分:1)
或者,让kurumi的解决方案更加冗长,并使用Jimmy的strftime:
histogram = dates.inject(Hash.new(0)) do |hist, date|
hist[date.strftime('%A %d')] += 1
hist
end.sort_by{|date, count| date.split(' ').last}.reverse
告诉我们:
Friday 28: 1
Thursday 27: 2
Wednesday 26: 1
Monday 24: 1
Friday 21: 2
OK?