I was playing to non-existence key of hash h1.but got surprised when i was seeing some errors and with their resolution.I wanted to know how the recursive call doing the job internally to handle the errors.
Part-I
here when tried h1[2][3] caused error. okay in next part I have resolved it.
irb(main):002:0> h1=Hash.new()
=> {}
irb(main):003:0> h1[2]
=> nil
irb(main):004:0> h1[2][3]
NoMethodError: undefined method `[]' for nil:NilClass
from (irb):4
from C:/Ruby193/bin/irb:12:in `<main>'
Part-II
Now how the Hash definition below handles the previous error. What internal algorithm ran,which was bot possible by Part-I. I know the below sysntx resolved it but i want to see internal screen how it has done job.
irb(main):005:0> h1 = Hash.new do |h,k|
irb(main):006:1* h[k] = Hash.new()
irb(main):007:1> end
=> {}
irb(main):008:0> h1[2]
=> {}
irb(main):009:0> h1[2][3]
=> nil
Can the recursive call be fixed? say h1[1][2][3] and h1[1][2][3][4] so on.
When I was calling Key by h1[2]- here i know that 2
is a key i was looking for.Now h1[1][2] - in that case the call looking for key with [1][2] - am I correct? If i am not correct then how the real thing is working from back-end - wanted to know that.
Can anyone help me here to understand?
Thanks,