Ruby hash error: undefined method [] when attempting to set deeply nested keys
hash, ruby
Solution
Hashes aren't nested by default. As `my_hash[first_key]` is not set to anything, it is `nil`. And `nil` is not a hash, so trying to access one of its elements fails.
So:
my_hash = {}
first_key = 1
second_key = 2
third_key = 3
my_hash[first_key] # nil
my_hash[first_key][second_key]
# undefined method `[]' for nil:NilClass (NoMethodError)
my_hash[first_key] = {}
my_hash[first_key][second_key] # nil
my_hash[first_key][second_key] = {}
my_hash[first_key][second_key][third_key] = 100
my_hash[first_key][second_key][third_key] # 100
Problem
I have a piece of code like this: ``` my_hash = {} first_key = 1 second_key = 2 third_key = 3 my_hash[first_key][second_key][third_key] = 100 ``` and the ruby interpreter gave me an error says that: undefined method `[]' for nil:NilClass (NoMethodError) So does it mean I cannot use hash like that? or do you think this error might because of something else?