16
17

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 5 years have passed since last update.

nilチェックの分岐をせずに文字列表示

Last updated at Posted at 2012-11-03

Objective-Cではnilに何を送ってもnilなのでnilチェックが不要ですが、Rubyはそうではないので文字列を表示する場合以下のような分岐が必要になってきます。

item.nil? '' ? item.created_at.strftime("%Y/%m/%d %H:%M")

こんなの毎回書いてたらうざいなー。いちいちモデルに表示用のメソッド定義するのもめんどいなー。

そんな時のためにRailsにはtryメソッドが定義されていました。

item.created_at.try(:strftime, "%Y/%m/%d %H:%M")

よかった。

16
17
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
16
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?