LoginSignup
22

More than 5 years have passed since last update.

二次元配列の初期化をmapで [Ruby]

Last updated at Posted at 2017-02-25

Rubyで競プロやってて二次元配列ミスったので共有する

間違えたパターン

3x3の2次元配列を作る

a = Array.new(3, Array.new(3, 0) )

これではアウト
第一要素の配列の状態を変更すると

a = Array.new(3, Array.new(3, 0) )

#変更前
p a
#第一要素の配列の変更 0 => 5
a[0][0] = 5
p a
results.
#変更前
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

#変更後
[[5, 0, 0], [5, 0, 0], [5, 0, 0]]

第一要素の配列のみに変更を行ったつもりが、他の配列にも影響を与えている。

なぜ?

最初の初期化で全て同じ配列オブジェクトを参照してしまっているため

object_idを確認すると

confirmation.
a = Array.new(3, Array.new(3, 0) )
p a.map(&:object_id)
result.
[70285890080600, 70285890080600, 70285890080600]

配列はすべて同じオブジェクトを参照してしまっている

mapメソッドを使って解決

個人的にmap好きなのでmap使います

map.
a = Array.new(3).map{Array.new(3,0)}

p a
a[0][0] = 5
p a
results.
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[5, 0, 0], [0, 0, 0], [0, 0, 0]]

mapを使うことで別々のオブジェクトとして定義したので、ほかの要素に影響を与えない

object_idを確認すると

confirmation.
a = Array.new(3).map{Array.new(3,0)}

p a.map(&:object_id)
result.
[70224619687520, 70224619687500, 70224619687480]

map洒落てるよね、好きです

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
22