In Ruby, why does Array.new(size, object) create an array consisting of multiple references to the same object?

前端 未结 3 1846
陌清茗
陌清茗 2020-11-30 14:19

As mentioned in this answer, Array.new(size, object) creates an array with size references to the same object.

hash =          


        
3条回答
  •  情书的邮戳
    2020-11-30 14:59

    I came up with this answer, very short and simple solution

    c_hash = Hash.new
    ["a","b","c","d","e","f"].each do |o|
      tmp = Hash.new
      [1,2,3].map {|r| tmp[r] = Array.new}
      c_hash[o] = tmp
    end
    c_hash['a'][1] << 10
    p c_hash
    

提交回复
热议问题