简体   繁体   English

如何将这些对象分组为哈希?

[英]How do I group these objects into a hash?

I have an event modal, which has a datetime field titled scheduled_time . 我有一个事件模式,它有一个名为scheduled_timedatetime字段。 I need to create a hash that has a day name in a certain format ('mon', 'tue' etc) as the key, and the count of events that take place on that day as the value. 我需要创建一个哈希,该哈希以特定格式(“ mon”,“ tue”等)作为日期名称,并以该天发生的事件计数作为值。 How can I do this? 我怎样才能做到这一点?

{
    'mon' => 2,
    'tue' => 4,
    'wed' => 3,
    'thu' => 5,
    'fri' => 12,
    'sat' => 11,
    'sun' => 7,
}

I'm using Rails 3.2.0 and Ruby 1.9.2 我正在使用Rails 3.2.0和Ruby 1.9.2

The easiest would be to use count with a :group option: 最简单的方法是将count:group选项一起使用:

h = Model.count(:group => %q{to_char(scheduled_time, 'dy')})

The specific function that you'd GROUP BY would, as usual, depend on the database; 通常,您要GROUP BY的特定功能取决于数据库;具体取决于数据库。 the to_char approach above would work with PostgreSQL, with MySQL you could use date_format and lower : 上面的to_char方法适用于PostgreSQL,而对于MySQL,则可以使用date_formatlower

h = Model.count(:group => %q{lower(date_format(scheduled_time, '%a'))})

For SQLite you'd probably use strftime with a %w format and then convert the numbers to strings by hand. 对于SQLite,您可能会使用%w格式的strftime ,然后手动将数字转换为字符串。

Note that using Model.count(:group => ...) will give you a Hash with holes in it: if there aren't any entries in the table for that day then the Hash won't have a key for it. 请注意,使用Model.count(:group => ...)将为您提供一个带孔的哈希:如果当天表中没有任何条目,则哈希将没有密钥。 If you really want seven keys all the time then create a Hash with zeros: 如果您确实一直想要七个键,则创建一个带有零的哈希值:

h = { 'mon' => 0, 'tue' => 0, ... }

and then merge the count results into it: 然后将count结果合并到其中:

h.merge!(Model.count(:group => ...))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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