简体   繁体   中英

Ruby count items by date

I have an array of dates eg

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
@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.

s=a.inject(Hash.new(0)) do |h,y|
    z=y.split
    h[ z[0]+z[2] ]+=1
    h
end

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM