Ruby/Rails using || to determine value, using an empty string instead of a nil value

后端 未结 3 626
无人共我
无人共我 2021-02-02 11:46

I usually do

 value = input || \"default\"

so if input = nil

 value = \"default\"

But how can I do this so in

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-02 12:19

    Rails adds presence method to all object that does exactly what you want

    input = ''
    value = input.presence || "default"
    => "default"
    
    input = 'value'
    value = input.presence || "default"
    => "value"
    
    input = nil
    value = input.presence || "default"
    => "default"
    

提交回复
热议问题