Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby hash error: undefined method []

Tags:

ruby

hash

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?

like image 221
Allan Jiang Avatar asked May 01 '12 01:05

Allan Jiang


1 Answers

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
like image 150
Russell Avatar answered Sep 23 '22 03:09

Russell