LoginSignup
15
6

More than 1 year has passed since last update.

#Ruby 配列/ハッシュでぼっち演算子を利用して nil エラーを防ぐ ( NoMethodError: undefined method `[]' for nil:NilClass )

Last updated at Posted at 2020-05-15

[] メソッド対して引数を与えれば良い

Array

[:a, :b, :c][0]
# => :a

nil[0]
# NoMethodError: undefined method `[]' for nil:NilClass

nil&.[](0)
# nil

Hash

{a: :x}[:a]
# => :x

nil[:a]
# NoMethodError: undefined method `[]' for nil:NilClass

nil&.[](:a)
# nil

Original by Github issue

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

15
6
0

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
15
6