Help us understand the problem. What is going on with this article?

rubyで配列の中にハッシュを初期化したい

More than 3 years have passed since last update.

概要

5つの配列の要素に対してハッシュで初期化したい。

ary = [{},{},{},{},{}]

これを作りたい。

正しい例

irbで実験。

ary = Array.new(5){{}}
=> ary = [{},{},{},{},{}]
ary[0][:hoge] = "test"
=> "test"
ary
=> [{:hoge=>"test"}, {}, {}, {}, {}]
上記はコメント頂いて修正したコードです。(2016/01/21)
# 記事初稿時のコード
ary = Array.new(5).map{Hash.new}

誤った例

irbで実験。

ary = Array.new(5, Hash.new)
=> ary = [{},{},{},{},{}]
ary[0][:hoge] = "test"
=> "test"
ary
=> [{:hoge=>"test"}, {:hoge=>"test"}, {:hoge=>"test"}, {:hoge=>"test"}, {:hoge=>"test"}]

同一を参照してしまうため、
意図しない挙動になってしまう。

sonoshou
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away