0
0

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 1 year has passed since last update.

ぼっち演算子

Posted at

ユーザーが存在しない

current_user = nil

ぼっち演算子なし

name = current_user.name
#=> undefined method `name' for nil:NilClass (NoMethodError)

ぼっち演算子あり

name = current_user&.name
#=> nil

まとめ

ぼっち演算子を使うと、エラーではなく、nilを返してくれる。
当然ながら、メソッドが存在しないとエラーになります。

簡単なように見えますが、落とし穴もあるみたいなので、注意して使いましょう。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?