简体   繁体   English

在Ruby中访问哈希中的数组

[英]Accessing an array within a hash in Ruby

I'm writing an application that pulls values out of an Excel spreadsheet and then stores those values in a hash using the version number as a key. 我正在编写一个应用程序,该应用程序将值从Excel电子表格中提取出来,然后使用版本号作为键将这些值存储在哈希中。 Everything seems to be working correctly until I try and retrieve the information from the hash. 直到我尝试从哈希中检索信息之前,一切似乎都正常运行。 Here is the code that builds the hash: 这是构建哈希的代码:

@version_numbers.each do |version|
   user_variables = Spreadsheet.open "#{version}.xls" #Opens excel sheet for all versions present 
   user_variables_sheet = user_variables.worksheet 0 #Loads worksheet
   user_variables_hash = {}

   user_variables_sheet.each 1 do |row| #Skips the first row containing titles
        part_number = row[0].to_i
        serial = row[1].to_i
        (user_variables_hash[version] ||= []) << [part_number, serial]
    end
end

When I try to retrieve the information from a 01-2 version using user_variables_hash['01-2'][0][0] , it produces an error that states: 当我尝试使用user_variables_hash['01-2'][0][0]从01-2版本检索信息时,会产生错误,指出:

undefined method '[]' for nil: NilClass (NoMethodError) 未定义的方法'[]'为nil:NilClass(NoMethodError)

Any help would be greatly appreciated. 任何帮助将不胜感激。

Thanks. 谢谢。

For each version number, you're creating a new empty hash ( user_variables_hash = {} ) and then inserting the version number into that new hash. 对于每个版本号,您要创建一个新的空哈希( user_variables_hash = {} ),然后将版本号插入该新哈希中。 This is almost certainly not what you want. 几乎可以肯定这不是您想要的。

You probably want to initialize user_variables_hash once before the each-loop. 您可能希望在每个循环之前初始化一次user_variables_hash

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM