开发者

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. 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:

undefined method '[]' for 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. This is almost certainly not what you want.

You probably want to initialize user_variables_hash once before the each-loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜