7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2016-01-21

概要

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"}]

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

7
7
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?