Ruby / Rails使用||使用空字符串而不是nil值来确定值

时间:2013-01-19 14:27:58

标签: ruby-on-rails ruby

我经常做

 value = input || "default"

所以如果输入= nil

 value = "default"

但是我怎么能这样做而不是nil它还将空字符串''计为nil

我希望如果我这样做

input = ''
value = input || "default"
=> "default"

在没有if的情况下,是否有一种简单优雅的方法?

3 个答案:

答案 0 :(得分:47)

Rails将presence方法添加到完全符合您要求的所有对象

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

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

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

答案 1 :(得分:3)

我通常这样做:

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

对于可能未定义输入的情况,您可以通过以下方式保护输入:

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

对于纯红宝石(不依赖于Rails),您可以使用empty?

value = input || (input.empty? ? "default" : input)
value = (input ||= "").empty? ? "default" : input # thanks gg_s for providing this

答案 2 :(得分:0)

也许是无关紧要但我会像这样使用高线:

require "highline/import"

input = ask('Input: ') { |q| q.default = "default" }

它没有Rails。真的很整洁。