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

前端 未结 4 1973
情歌与酒
情歌与酒 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:06

    When you write,

    h = Hash.new([])
    

    you pass default reference of array to all elements in hash. because of that all elements in hash refers same array.

    if you want each element in hash refer to separate array, you should use

    h = Hash.new{[]} 
    

    for more detail of how it works in ruby please go through this: http://ruby-doc.org/core-2.2.0/Array.html#method-c-new

提交回复
热议问题