Please follow the below code :
Part-I
> h = { "a" => 100, "b" => 200 }
=> {"a"=>100, "b"=>200}
> h.default = "Go fish"
=> "Go fish"
> h["a"]
=> 100
> h["z"]
=> "Go fish"
> h.default = proc do |hash, key|
* hash[key] = key + key
> end
=> #<Proc:0x208bee8@(irb):5>
> h[2]
=> #<Proc:0x208bee8@(irb):5>
> h["cat"]
=> #<Proc:0x208bee8@(irb):5>
Part-II
> h = { "a" => 100, "b" => 200 }
=> {"a"=>100, "b"=>200}
> h.default_proc = proc do |hash, key|
* hash[key] = key + key
> end
=> #<Proc:0x1e21df8@(irb):2>
> h[2]
=> 4
> h["cat"]
=> "catcat"
Now I am surprised to see, why h[2] and h["cat"] giving different output for the two codes in part-I and part-II.
Could you anyone please explain?
Hash#default=sets the value to be returned in case there is no such key. You set that to a proc in Part-I, and that is what you see being returned.Hash#default_proc=sets the proc to be called on itself and the key in case there is no such key. If you dohash[2] = 2 + 2, thenhash[2]will return4. If you dohash["cat"] = "cat" + "cat", thenhash["cat"]will return"catcat".