use*_*752 17 ruby testing conditional spaces
所以我在ruby中知道x.nil?将测试x是否为null.
测试x等于'',''(两个空格)或''(三个空格)等的最简单方法是什么?
基本上,我想知道测试变量是否都是空白的最佳方法是什么?
Mik*_*keJ 31
如果您使用的是Rails,则只需使用:
x.blank?
Run Code Online (Sandbox Code Playgroud)
当x为nil时调用是安全的,如果x为nil或所有空格,则返回true.
如果你不使用Rails,你可以从activesupportgem 获得它.安装时gem install activesupport.在您的文件中,要么require 'active_support/core_ext获得基类的所有活动支持扩展,要么require 'active_support/core_ext/string'只获取String类的扩展.无论哪种方式,该blank?方法将在要求之后可用.
jsh*_*hen 23
"最好"取决于上下文,但这是一个简单的方法.
some_string.strip.empty?
Run Code Online (Sandbox Code Playgroud)
Ste*_*all 16
s =~ /\A\s*\Z/
Run Code Online (Sandbox Code Playgroud)
正则表达式解决方案.这是一个简短的ruby正则表达式教程.
如果x是所有空格,那么x.strip将是空字符串.所以你可以这样做:
if not x.nil? and x.strip.empty? then
puts "It's all whitespace!"
end
Run Code Online (Sandbox Code Playgroud)
或者,使用正则表达式,x =~ /\S/当且仅当x所有空格字符都返回false时:
if not (x.nil? or x =~ /\S/) then
puts "It's all whitespace!"
end
Run Code Online (Sandbox Code Playgroud)