10
9

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 5 years have passed since last update.

nilに対してメソッドを使った時のエラーの回避方法 (ぼっち演算子「&」使い方)

Last updated at Posted at 2019-06-20

ぼっち演算子の使い方をアウトプットしてみた。

例)
Deviseを使用したときのcurrent_userに対して、nicknameカラムに
あるデータを取得して@ nicknameに代入することを意図したコードがある。

@nickname = current_user.nickname

このような記述の場合、ログインしていない時に、これを実行するとnilに対してメソッドを使おうとしてエラーになってしまう。このようなエラーをぼっち演算子を用いて、回避する方法を解説する。

ぼっち演算子とは何か?

ぼっち演算子とは、オブジェクトの中身がnil(空、値が代入されていない)の場合に、nilという値変換して、nilという値をオブジェクトに代入する演算子をいう。別名では、Null条件演算子と言われることもある。

Railsの場合、Rubyは2.3.0以降から、& 「アンパサンド」というぼっち演算子が使用できるようになっている。

ぼっち演算子「&」使い方

@nickname = current_user&.nickname

current_userというメソッドに続けて&を記述するだけで完了する。

処理の流れは、
current_userメソッドがに値が代入されている(nilではない)場合のみ、右辺のメソッドが実行される。そして、もしnilであった場合は、全ての演算結果としてnilを返すことになる。つまり、@ nicknameにnilというが代入される。

<参考記事>
https://kossy-web-engineer.hatenablog.com/entry/2018/09/20/060701
https://ja.wikipedia.org/wiki/Null%E6%9D%A1%E4%BB%B6%E6%BC%94%E7%AE%97%E5%AD%90
https://matt-note.hatenadiary.jp/entry/2018/11/14/083307

10
9
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
10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?