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.

【Rails】try / try! / &.ぼっち演算子

Posted at

##try

定義してないメソッドに対してnilを返す

User.first.try(:email)
# => "abc@gmail.com"
User.first.try(:aaa)
# => nil
nil.try(:email)
# => nil

##try!

定義してないメソッドに対してNoMethodErrorを返す

User.first.try!(:email)
# => "abc@gmail.com"
User.first.try!(:aaa)
# NoMethodError: undefined method `aaa' for #<User:0x000055eafbb7a4d0>
nil.try!(:email)
# => nil

##&.

基本的にtry!と同じ挙動

Employee.find_by(firstname: 'コナン')&.email || 'コナンというユーザーは存在しません'
# => "conan@gmail.com"
Employee.find_by(firstname: 'コナン')&.email || 'コナンというユーザーは存在しません'
# => "コナンというユーザーは存在しません"
Employee.find_by(firstname: 'コナン')&.aaa
# NoMethodError: undefined method `aaa' for #<User:0x000055eafb23fc30>

##参考

0
0
1

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?