0

I have the following examples:

a = Hash.new([])
a[2][1] = 10
a[2] # => [nil, 10]
a # => {}

Why is the default hash not modified? How are the keys not able to be found? Why can't I see or iterate over any keys, but can call them via their index?

sawa
  • 165,429
  • 45
  • 277
  • 381
Mike H-R
  • 7,726
  • 5
  • 43
  • 65
  • 1
    This question was asked too many time.. But to answer you `Hash.new { |h,k| h[k] = [] }` – Arup Rakshit Jan 29 '16 at 11:50
  • 2
    explanation http://stackoverflow.com/questions/2698460/strange-behavior-when-using-hash-default-value-e-g-hash-new – Arup Rakshit Jan 29 '16 at 11:54
  • 1
    I am not sure if it is a duplicate, and I can't find a good answer in the linked question. So I answer here: You are modifying the default array, but that default array itself is never assigned as a value of the original hash under any key. What you see with `a[2]` is not the `2`-key value of `a`, but merely the default value of `a`. – sawa Jan 29 '16 at 12:03
  • @ArupRakshit Thanks for the reference. – Mike H-R Jan 29 '16 at 12:09
  • @sawa Thanks for the additional explanation. – Mike H-R Jan 29 '16 at 12:09
  • @sawa Myself only answers to such questions many times, but not able to find the link :) – Arup Rakshit Jan 29 '16 at 12:11

0 Answers0