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

In my app I want to prevent a variable from being blank — eg, a user's name should be something other than spaces and other whitespace. It will work like this:

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

Rails adds blank? method to class String , so that "".blank? , " ".blank? , and nil.blank? are all true . Ruby has similar empty? method, but it differs from blank? , as we can see in the example below (this won't work in plain irb ):

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

We see that a string of spaces is not empty, but it is blank.

Your solutions?

PS I gonna do this in pure Ruby, not in Rails.


If you want something exactly like rails you could require activesupport. Or, if something simpler can go, you could do

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

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

The regex is taken from rails.


In addition to Gopal's answer (as I cannot comment yet):

I would also use String.strip before checking on empty.

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

Better open the predefined String class and implement that method

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

and also NilClass

class NilClass
  def blank?
    return true
  end
end

Now you can use the blank? function in your code.

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

上一篇: 了解Rails真实性令牌

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