我有一个关于从散列中检索信息的快速问题,这是迄今为止的代码:
permits_sheet.each do |row|
rate_type = row[0].to_s #Converts the rate type (title) to a string
row.shift #Removes the title from hash so it's not added to values
row.each do |values|
split_value = values.split ('=') #References relations from an excel sheet pulled in earlier. EG: T=2324, W=8633
(@@permits_hash[rate_type] ||= []) << {split_value[0].to_s => split_value[1]} #Multiple values exist within each title
end
end
puts @@permits_hash['R']['T'] #In this example I'm searching for the hash key of T under the R title. I expected it to return the 2324 from the example above.
尝试以这种方式检索信息时会导致错误。我确信我只是做了一些愚蠢的事情,但是非常感谢任何帮助(很长一段时间没有使用过Ruby)。
感谢您的帮助!
答案 0 :(得分:2)
如何不将哈希存储在数组中,而是像嵌套哈希一样?
(@@permits_hash[rate_type] ||= {})[split_value[0].to_s]=split_value[1]]
并不是说它有助于提高可读性,但实际上我认为你可以把这两个循环写成一个单行。
@@permits_hash=Hash.new
row=["title","k1=v2","k2=v2","k3=v3"]
# Here's the line replacing the two loops
(@@permits_hash[row.shift] ||= {}).update(Hash[*row.map{|v| v.split("=")}.flatten])
>> @@permits_hash
=> {"title"=>{"k1"=>"v2", "k2"=>"v2", "k3"=>"v3"}}