Ruby-on-rails 测试空或零值字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15988960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:48:40  来源:igfitidea点击:

Testing for empty or nil-value string

ruby-on-railsruby

提问by Richard Brown

I'm trying to set a variable conditionally in Ruby. I need to set it if the variable is nil or empty (0 length string). I've come up with the following:

我正在尝试在 Ruby 中有条件地设置一个变量。如果变量为 nil 或空(0 长度字符串),我需要设置它。我想出了以下几点:

variable = id if variable.nil? || (!variable.nil? && variable.empty?)

While it works, it doesn't seem very Ruby-like to me. Is the a more succinct way of expressing the above?

虽然它有效,但对我来说似乎不太像 Ruby。以上是不是更简洁的表达方式?

回答by Jon Gauthier

The second clause does not need a !variable.nil?check—if evaluation reaches that point, variable.nilis guaranteed to be false (because of short-circuiting).

第二个子句不需要!variable.nil?检查——如果评估达到那个点,variable.nil保证是假的(因为短路)。

This should be sufficient:

这应该足够了:

variable = id if variable.nil? || variable.empty?


If you're working with Ruby on Rails, Object.blank?solves this exact problem:

如果您正在使用 Ruby on Rails,Object.blank?可以解决这个确切的问题:

An object is blank if it's false, empty, or a whitespace string. For example, "", " ", nil, [], and {}are all blank.

如果对象为 false、空或空白字符串,则该对象为空。例如""" "nil[],和{}都是空白。

回答by Adrian Teh

If you're in Rails, .blank?should be the method you are looking for:

如果你在 Rails 中,.blank?应该是你正在寻找的方法:

a = nil
b = []
c = ""

a.blank? #=> true
b.blank? #=> true
c.blank? #=> true

d = "1"
e = ["1"]

d.blank? #=> false
e.blank? #=> false

So the answer would be:

所以答案是:

variable = id if variable.blank?

回答by sawa

variable = id if variable.to_s.empty?