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

后端 未结 3 579
无人共我
无人共我 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:06

    Maybe irrelavant but I would use highline like this:

    require "highline/import"
    
    input = ask('Input: ') { |q| q.default = "default" }
    

    It works without Rails. Really neat solution.

    0 讨论(0)
  • 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"
    
    0 讨论(0)
  • 2021-02-02 12:20

    I usually do in this way:

    value = input.blank? ? "default" : input
    

    In response to the case that input might not be defined, you may guard it by:

    value = input || (input.blank? ? "default" : input)
    # I just tried that the parentheses are required, or else its return is incorrect
    

    For pure ruby (not depending on Rails), you may use empty? like this:

    value = input || (input.empty? ? "default" : input)
    

    or like this (thanks @substantial for providing this):

    value = (input ||= "").empty? ? "default" : input
    
    0 讨论(0)
提交回复
热议问题