LoginSignup
0
0

More than 5 years have passed since last update.

[ruby] nil状態でメソッドの呼び出しを行わない  tryメソッド

Posted at

tryメソッド

tryメソッドを使うためにはActive Supportをインストールする

gem install activesupport

違いは以下。
シンプルにかけていいね

user ? user.address : '住所不定'
user.try(:address) || '住所不定'

tryとtry!の違い

1.userがnilの時、何もしない
2.userにaddressが実装されてない時、何もしない

1,2両方の効用を持つのがtryであり、1つ目の効用しか持たないのが try!です。
tryを使う目的としては、1が多いと思いますので、積極的にtry!を使うほうがよいでしょう。

なるほどとりあえずtry!を使えばいいのね

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