在ruby 1.8.7中操作有序哈希

时间:2011-12-16 07:14:40

标签: ruby-on-rails ruby hash

我有以下查询返回有序哈希

counts = VideoLog.count(
    :conditions =>["question_id = ? AND user_id = ? AND created_at >= ? AND created_at <= ? AND dashboard = ? AND watched = ?", video.id,current_user.id, @start_date, @end_date, "#{@dashboard}", 1],
    :group      => "created_at"
  )

count是一个有序的哈希:

{Wed Nov 30 07:37:36 UTC 2011=>1, Fri Nov 18 11:01:05 UTC 2011=>1, Wed Nov 30 07:38:16 UTC 2011=>1}

我希望将其索引修改为特定时区,然后将它们转换为仅限日期,然后迭代它们,我该怎么做?

2 个答案:

答案 0 :(得分:2)

您没有指定要对重复键执行的操作,我假设您要对它们求和。所以:

h = {"Wed Nov 30 07:37:36 UTC 2011"=>1, "Fri Nov 18 11:01:05 UTC 2011"=>1, "Wed Nov 30 07:38:16 UTC 2011"=>1}

h.inject(Hash.new 0) do |res, pair|
  res[Time.parse(pair.first).in_time_zone("Europe/Paris").to_date] += pair.last; res
end

,结果是

=> {Wed, 30 Nov 2011=>2, Fri, 18 Nov 2011=>1}

答案 1 :(得分:0)

这样的事情会起作用:

counts.each do |key,value|
    key = Date.parse key.localtime("+12:00").to_s
    # do something
end