Ruby按日期计算项目 [英] Ruby count items by date

查看:201
本文介绍了Ruby按日期计算项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,例如

  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 
星期四27 => 2
星期三26 => 1
星期一24 => 1
星期五21 => 2


解决方案

或者,将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

给我们:

 星期五28:1 
星期四27:2
星期三26:1
星期一24:1
星期五21:2

确定?


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

解决方案

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?

这篇关于Ruby按日期计算项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆