試試這個:
h = Hash.new {|h1, k1| h1[k1] = Hash.new{|h2, k2| h2[k2] = []}}
result, today = [ h, h.dup], Date.today
Request.find_all_by_artist("Metallica",
:select => "DISTINCT venue, showdate, LOWER(song) AS song"
).each do |req|
idx = req.showdate < today ? 0 : 1
result[idx][req.venue][req.showdate] << req.song.titlecase
end
注1
在第一行中,我正在初始化散列哈希。外部哈希在訪問不存在的密鑰時創建內部哈希。從紅寶石哈希documentation的摘錄:
If this hash is subsequently accessed by a key that doesn‘t correspond to a hash
entry, the block will be called with the hash object and the key, and should
return the default value. It is the block‘s responsibility to store the value in
the hash if required.
內散列創建並當不存在的日期被訪問空數組。
例如:構建含有的內容的值和日期作爲密鑰的散列:
如果沒有默認塊:
h = {}
list.each do |data|
h[data.date] = [] unless h[data.date]
h[data.date] << data.content
end
隨着默認塊
h = Hash.new{|h, k| h[k] = []}
list.each do |data|
h[data.date] << data.content
end
第二行簡單創建一個包含兩個項目的數組來保存過去和將來的數據。既然過去和現在都將數據存儲爲數組散列哈希,我只需複製該值。
第二行也可以寫成
result = [ h, h.dup]
today = Date.today
是如何從你的最後一個問題,這個不同的http://stackoverflow.com/questions/3891231/how-do-i-create-this-multidemsional- array-hash-combo – 2010-10-09 03:44:32
它的不同,因爲我需要現在把它分解成兩個數組,我不想重複邏輯,如果我可以幫助它 – Trace 2010-10-09 03:52:45
@KandadaBoggu - 也欣賞你對上一個問題的答案..謝謝很多 – Trace 2010-10-09 03:54:10