2010-09-21 80 views
0

我从一个哈希检索信息快速的问题,这里是代码至今:检索从哈希信息散列内 - 红宝石

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

这将是有益的,如果你能发布的错误信息。 – 2010-09-21 19:32:09

+0

Test.rb:117:in'[]':无法将字符串转换为整数(TypeError) 所有内容都已转换为字符串,所以我遇到了一些排查问题的问题。 – 2010-09-21 19:34:30

+0

您正在使用字符串为数组建立索引。 – yxhuvud 2010-09-21 19:41:26

回答

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

+0

你先生,是个绅士和学者。这正是我一直在寻找的,但我一直盯着屏幕这么久,我只是不记得如何正确地做到这一点。 再次感谢您的帮助! – 2010-09-21 19:56:12

+0

谢谢,还添加了一行。 – 2010-09-21 20:17:03

+2

@Ruby新手:如果乔纳斯解决了你的问题(因为它出现),你会很高兴通过点击答案左边的复选标记来接受他的答案。 – 2010-09-21 20:18:14