Ruby:如何检查一个字符串是否不为空?

在我的应用程序中,我想防止变量变为空白 - 例如,用户的名称应该是空格和其他空格以外的内容。 它会像这样工作:

foobar = gets.strip
arr = []
if # the string in the variable 'foobar' isn't blank
    arr.push(foobar)
end

Rails添加blank? 方法来类String ,这样"".blank?" ".blank?nil.blank? 都是true 。 Ruby有类似的empty? 方法,但它不同于blank? ,正如我们在下面的例子中可以看到的(这在普通的irb不起作用):

>> "      ".empty?
=> false
>> "      ".blank?
=> true

我们看到一串空格不是空的,而是空白的。

你的解决方案

PS我会在纯Ruby中做到这一点,而不是在Rails中。


如果您想要像Rails一样的东西,您可能需要有效的支持。 或者,如果更简单的事情可以去,你可以做

class String
  BLANK_RE = /A[[:space:]]*z/

  def blank?
    BLANK_RE.match?(self)
  end
end

正则表达式是从rails中取出的。


除了Gopal的回答(因为我还没有评论):

我也会在检查空之前使用String.strip。

class String
    def blank? { self.strip.empty? }
end

最好打开预定义的String类并实现该方法

class String
  def blank?
    if strip.empty?
      return true
    end
  end
end

还有NilClass

class NilClass
  def blank?
    return true
  end
end

现在你可以使用空白? 函数在你的代码中。

链接地址: http://www.djcxy.com/p/25801.html

上一篇: Ruby: How to check whether a string isn't blank?

下一篇: Duplicating .blank? in standard Ruby