带空字符串的条件赋值

red*_*Fur 2 ruby ruby-on-rails

我喜欢Ruby中的条件赋值语法并且一直使用它:

x = this_var || that_var
Run Code Online (Sandbox Code Playgroud)

现在我正在使用几个API,它们为不存在的值返回空字符串.由于在Ruby中空字符串的计算结果为true,因此我无法再使用上述语法来设置默认值.当我有几个默认值"级别"时会变得更糟,例如"如果此var不存在则将其设置为该var,如果不存在,则将其设置为另一个var".所以我最终这样做:

x = if this_var.present?
       this_var
    elsif that_var.present?
       that_var
    else
       last_resort
    end
Run Code Online (Sandbox Code Playgroud)

.present?方法有所帮助,但并不多.我怎么用更简洁的方式写这样的东西?

我正在使用Rails 4,所以欢迎Rails方法作为答案:)

谢谢

Ser*_*sev 10

这是你使用present?兄弟的地方presence(假设你使用rails或至少是主动支持).

x = this_var.presence || that_var.presence || last_resort
Run Code Online (Sandbox Code Playgroud)


saw*_*awa 5

x = [this_var, that_var, last_resort].find(&:present?)
Run Code Online (Sandbox Code Playgroud)