Ravi kumar Ravi kumar - 6 months ago 11
Ruby Question

Need to understand hash of hashes in ruby

I came to know that we can create hash of hashes as below:

Hash.new{|hash, key| hash[key] = Hash.new}


But I dont understand whether the key and value getting converted as hash. Can someone explain me in brief about this.

Answer

If you define hash this way, ruby set the default value on every key in hash to new hash and save it.

sample

h = Hash.new{|hash, key| hash[key] = Hash.new}

h[:foo]
# => {}
p h
# => {:foo=>{}}

insted of define only default value

h = Hash.new({})

h[:foo]
# => {}
p h
# => {}