a.try(:hoge) #=> nil a.try!(:hoge) #=> NoMethodError はーぁん、にゃーるほーどねー。 これ見て初めて気付いたのですが、 「try メソッドには 2 つの効用がある」 のですね。 a が nil の時、何もしない a に hoge が実装されてない時、何もしない 両方の効用を持つのが try 1 つ目の効用しか持たないのが try! というわけです。 2 つ目の効用も便利っちゃあ便利ですが、メソッド名を typo するとわかりづらいバグになることもありそうです。 実際 try を使うときは、レシーバ (上の例で a ) が nil かどうかで使う 1 つ目の効用を利用したい場合が殆どだと思われるので、積極的に try! を使っていくといいかと思います。 ruby2.3記念追記 rails にまず導入されたのが try で、その後、「NoMe
I sometimes write following code with rails application: u = User.find(id) if u && u.profile && u.profile.thumbnails && u.profiles.thumbnails.large ... or # Use ActiveSupport if u.try!(:profile).try!(:thumbnails).try!(:large) ... I hope to write shortly above code. Groovy has above operator named "Safe navigation operator" with "?." syntax. Ruby can't use "?." operator. Can we use ".?" syntax. lik
リリース、障害情報などのサービスのお知らせ
最新の人気エントリーの配信
処理を実行中です
j次のブックマーク
k前のブックマーク
lあとで読む
eコメント一覧を開く
oページを開く