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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With