Ruby - Array With Default Value Feb 4th, 2019 6:10 pm | Comments Array.new 可以建立一個長度的 default value 這樣建立的話會對應到一樣的 object 1 2 3 4 5 6 7 a = Array.new(2, Hash.new) # => [{}, {}] a[0]['animal'] = 'dog' # => "dog" a # => [{"animal"=>"dog"}, {"animal"=>"dog"}] a[1]['animal'] = 'cat' # => "cat" a # => [{"animal"=>"cat"}, {"animal"=>"cat"}] 必須給 block 每個 object 才會是獨立的 1 2 3 a = Array.new(2) { Hash.new } # => [{}, {}] a[0]['animal'] = 'dog' # => "dog" a # => [{"animal"=>"dog"}, {}] 參考文件 Array new