LoginSignup
20
13

More than 5 years have passed since last update.

nilまたは空白の場合にデフォルト値を返す

Last updated at Posted at 2012-10-10
blank_or_value.blank? ? 'Default' : blank_or_value

のように書かざるを得ないところを

blank_or_value.presence || 'Default'

と書ける

ちなみにRails 2.3.8くらいから

.presence || でつなげるのかっこいいな

参考:Stackoverflow(If string is empty then return some default value)

この書き方を調べたきっかけは、みな良く知っていて最も良く使われる以下の表現

nil_or_value || 'Default'

他にも関連する例を挙げておくと

@nil_or_value ||= 'default value'

nil_or_object.try(:hoge)

blank_or_value.present?
20
13
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
20
13