2011-12-16 117 views
0

我有一個返回有序散列操縱有序散列紅寶石1.8.7

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" 
) 

計數下面的查詢是一個有序的哈希:

{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

你沒有指定你想用重複的鍵做什麼,我假設你想對它們進行求和。所以:

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} 
+0

這是很酷的,多謝;) – 2011-12-16 10:44:46

0

像這樣將工作:

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