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

Rubyのぼっち演算子(&.)にはメソッドだけでなく演算子も渡せる

Last updated at Posted at 2021-03-26

Rubyでは、あるオブジェクトのメソッドやインスタンスのインスタンス変数にアクセスする際、アクセス元(レシーバーというそうです)がnilの場合はエラーとなる。それを防ぐために返り値wをnilを変えるのが&.演算子です(self navigation operator, ぼっち演算子というらしい)


# もし@userが未定義(nil)のとき
article = @user.article  # => NoMethodError: undefined method `artcile' for nil:NilClass
article = @user&.article # => nil

これはメソッドにも演算子に対しても使えます
演算子もいくつかを除いてメソッドとして実装されているため、同じ挙動をします


nil + 10   # => NoMethodError: undefined method `+' for nil:NilClass
nil &.+ 10 #=> nil

nil << 10   # => NoMethodError: undefined method `<<' for nil:NilClass
nil &.<< 10 # => nil

# 次の2つの式が同値になる
@user.article && @user.article == Article.last
@user.article &.== Article.last

0
0
5

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?