Ruby hash error: undefined method []

I have a 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 message:

undefined `[] 'method for nil: NilClass (NoMethodError)

So does this mean that I cannot use the hash? or do you think this error may be caused by something else?

+7
source share
4 answers

Hashes are not nested by default. Since my_hash[first_key] not configured for anything, this is nil . And nil 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 
+10
source

The way you use the hash is not valid in Ruby, because each individual value must be assigned to the hash first before moving on to the nested hash (I assume you were with PHP?), But you can use a virtualized hash:

 my_hash = Hash.new{|h,k| h[k]=Hash.new(&h.default_proc)} first_key = 1 second_key = 2 third_key = 3 my_hash[first_key][second_key][third_key] = 100 p my_hash #output: {1=>{2=>{3=>100}}} 

So it will be convenient for you.

+7
source

You cannot use such hashes; my_hash[first_key] is zero, and then the next indexing operation fails. You can make a hash object that behaves the way you look - see http://taw.blogspot.co.uk/2006/07/autovivification-in-ruby.html - but it's not clear that this is a good style.

+2
source

You can do something like

 class NilClass def [] key nil end end 

in initializers like nil_overrides.rb and you can use nil['xxx'] .

0
source

All Articles