2
1

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.

ぼっち演算子とtryメソッドの違い

Posted at

共通点

レシーバがnilの場合は、nilを返す

foo = nil

foo.try(:bar)
#=> nil

foo&.bar
#=> nil

相違点

  • レシーバがnilで無く、レシーバが呼び出せないメソッドを呼び出してしまった場合
    • ぼっち演算子: NoMethodErrorを返す
    • tryメソッド: nilを返す
# レシーバが呼び出すこの出来ないbarメソッドを呼び出した場合

foo&.bar
#=> NoMethodError

foo.try(:bar)
#=> nil

まとめ

必ずしも、似てはいるけど同じでは無いってことですね。

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?