0
0

More than 1 year has passed since last update.

array pushってこんな動きだったっけ? 🤔

Last updated at Posted at 2023-02-14

なんかおもったプッシュと違う

さっそくコードと結果

@select_count = Array.new(9, [])

p @select_count[8]
p @select_count[8].push(38)
p @select_count

予想してた結果

[]
[38]
[[], [], [], [], [], [], [], [], [38]]

結果

[]
[38]
[[38], [38], [38], [38], [38], [38], [38], [38], [38]]

なんでこうなったか

2次元配列の初期化の方法が間違っていた

@select_count = Array.new(9){ Array.new() }

p @select_count[8]
p @select_count[8].push(38)
p @select_count

結果

[]
[38]
[[], [], [], [], [], [], [], [], [38]]

予想通りになりました。

まとめ

pushはまちがってなかった
初期化がまちがってました

でもなんで全部に38が反映されるかロジックは謎のままにしてます

なんで全部に38が反映されるか

気になってオブジェクトのIDだしてみたら
同一のオブジェクトが生成されるみたいでした。

@select_count = Array.new(9, [])

p @select_count[5].object_id
p @select_count[6].object_id
p @select_count[7].object_id
p @select_count[8].object_id


60
60
60
60
@select_count = Array.new(9){ Array.new() }

p @select_count[5].object_id
p @select_count[6].object_id
p @select_count[7].object_id
p @select_count[8].object_id

80
100
120
140
0
0
1

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
0
0