我有这个代码here,它可以工作,但必须有一个更好的方法.我需要两个数组,看起来像这样
[
{
"Vector Arena - Auckland Central, New Zealand" => {
"2010-10-10" => [
"Enter Sandman",
"Unforgiven",
"And justice for all"
]
}
},
{
"Brisbane Entertainment Centre - Brisbane Qld, Austr..." => {
"2010-10-11" => [
"Enter Sandman"
]
}
}
]一个是过去的问题,另一个是我的upcoming...the问题,我正在重复自己,尽管它可以工作,但我想要清理它,...here是我的data。
发布于 2010-10-09 11:56:41
试试这个:
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
在第一行中,我初始化了一个散列的散列。外部散列在访问不存在的键时创建内部散列。摘自Ruby Hash 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第二行简单地创建一个包含两个项的数组来保存过去和将来的数据。由于过去和现在都将数据存储为数组的Hash of Hash,所以我只是简单地复制值。
第二行也可以写成
result = [ h, h.dup]
today = Date.todayhttps://stackoverflow.com/questions/3895613
复制相似问题