LoginSignup
0
0

More than 3 years have passed since last update.

配列に第二引数まで使って初期を設定する際の注意点は各要素が同じobject_idだということ

Last updated at Posted at 2019-07-13

言いたいことはタイトル通りです。

Rubyの場合、配列はArray.newで生成でき、引数を2つ指定することで生成できます。

p tests = Array.new(5,'test')

=> ["test", "test", "test", "test", "test"]

第一引数に、要素数、第二引数には格納する文字列を指定できます。

注意点は各要素が同じobject_idであることです。

tests.each { |t| p t.object_id }

=> 70112523450820 # tests[0]
=> 70112523450820 # tests[1]
=> 70112523450820 # tests[2]
=> 70112523450820 # tests[3]
=> 70112523450820 # tests[4]

問題点は、破壊的メソッドで、どれかの要素を変えてしまうと、他の要素も変わってしまうことです。

p tests = Array.new(5,'test')
=> ["test", "test", "test", "test", "test"]

tests[0].upcase!

p tests
=> ["TEST", "TEST", "TEST", "TEST", "TEST"]

問題を避けたい場合は、ブロックで初期値を設定するといいです。

p tests= Array.new(5) { 'test' }
=> ["test", "test", "test", "test", "test"]

tests.each { |t| p t.object_id }
=> 70348531944080 # tests[0]
=> 70348531944060 # tests[1]
=> 70348531943940 # tests[2]
=> 70348531943900 # tests[3]
=> 70348531943880 # tests[4]
# それぞれ、object_idが違うので↑、破壊的メソッドで1つの要素変えても他に影響はありません。↓

tests[0].upcase!
p tests
=> ["TEST", "test", "test", "test", "test"]

同じオブジェクトかどうかを意識しないと、不具合を起こしてしまう可能性がありますので、注意が必要ですね。
メソッド object_idを使うと、同じかどうか確認できるので、慣れるまでは使って確認するのもありかと思います。

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