Tom
Tom

Reputation: 34366

Ruby count items by date

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

Upvotes: 1

Views: 263

Answers (3)

edavey
edavey

Reputation: 394

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?

Upvotes: 1

kurumi
kurumi

Reputation: 25599

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

Upvotes: 1

Jimmy
Jimmy

Reputation: 9815

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

Upvotes: 1

Related Questions