Strange, unexpected behavior (disappearing/changing values) when using Hash default value, e.g. Hash.new([])

前端 未结 4 1866
情歌与酒
情歌与酒 2020-11-21 11:31

Consider this code:

h = Hash.new(0)  # New hash pairs will by default have 0 as values
h[1] += 1  #=> {1=>1}
h[2] += 2  #=> {2=>2}
4条回答
  •  离开以前
    2020-11-21 12:16

    You're specifying that the default value for the hash is a reference to that particular (initially empty) array.

    I think you want:

    h = Hash.new { |hash, key| hash[key] = []; }
    h[1]<<=1 
    h[2]<<=2 
    

    That sets the default value for each key to a new array.

提交回复
热议问题