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.

ぼっち演算子 (&.)

Posted at

現場で使える Ruby on rails 5 速習実践ガイドの参考書で学んだぼっち演算子(&.)を勉強の記録用として記事にしてみました。

#ぼっち演算子 (&.) とは
&.という演算子を使ってメソッドを呼び出すと、レシーバーがnilであった場合でもエラーが発生しなくなります。

class User
  def name
    '名前'
  end
end
> user = User.new
> user.name
=> '名前'


#①
> object = nil
> object&.name
=> nil

#②
> object.name
Traceback (most recent call last):
...
NoMethodError (undefined method `name' for nil:NilClass)

②ではぼっち演算子を使わず、レシーバーであるオブジェクトがnilの場合はエラーになります。
①ではぼっち演算子を使うことでnilが返ってきてエラーにはなりません。

#参考
・現場で使える Ruby on rails 5 速習実践ガイド

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?