Ruby count items by date

2019-07-28 04:01发布

I have an array of dates e.g.

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

How can I group them so the output is as hash with the count of items each day:

Friday 28 => 1
Thursday 27 => 2
Wednesday 26 => 1
Monday 24 => 1
Friday 21 => 2

3条回答
对你真心纯属浪费
2楼-- · 2019-07-28 04:41
@things.group_by {|thing| thing.strftime "%A %d" }.each do |key, group|
  puts "#{key} => #{group.size}"
end

%A is the full weekday name and %d is the day of the month

I can't test this currently but I think it will work.

查看更多
再贱就再见
3楼-- · 2019-07-28 04:52
s=a.inject(Hash.new(0)) do |h,y|
    z=y.split
    h[ z[0]+z[2] ]+=1
    h
end
查看更多
等我变得足够好
4楼-- · 2019-07-28 04:54

Or, to put kurumi's solution more verbosely and using Jimmy's 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

give us:

Friday 28: 1
Thursday 27: 2
Wednesday 26: 1
Monday 24: 1
Friday 21: 2

OK?

查看更多
登录 后发表回答