So I know in ruby that x.nil? will test if x is null.
What is the simplest way to test if x equals ' ', or ' '(two spaces), or ' '(three spaces), etc?
Basically, I'm wondering what the best way to test if a variable is all whitespace?
So I know in ruby that x.nil? will test if x is null.
What is the simplest way to test if x equals ' ', or ' '(two spaces), or ' '(three spaces), etc?
Basically, I'm wondering what the best way to test if a variable is all whitespace?
If x
is all whitespace, then x.strip
will be the empty string. So you can do:
if not x.nil? and x.strip.empty? then
puts "It's all whitespace!"
end
Alternatively, using a regular expression, x =~ /\S/
will return false if and only if x
is all whitespace characters:
if not (x.nil? or x =~ /\S/) then
puts "It's all whitespace!"
end
s =~ /^\s*$/
Regex solution. Here's a short ruby regex tutorial.
Based on your comment I think you can extend the String class and define a spaces?
method as follows:
$ irb
>> s = " "
=> " "
>> s.spaces?
NoMethodError: undefined method `spaces?' for " ":String
from (irb):2
>> class String
>> def spaces?
>> x = self =~ /^\s+$/
>> x == 0
>> end
>> end
=> nil
>> s.spaces?
=> true
>> s = ""
=> ""
>> s.spaces?
=> false
>>
"best" depends on the context, but here is a simple way.
some_string.strip.empty?
If you are using Rails, you can simply use:
x.blank?
This is safe to call when x is nil, and returns true if x is nil or all whitespace.
If you aren't using Rails you can roll your own by copying the Rails source. Install Rails 2.3.5 then look at yourrubydir\lib\ruby\gems\1.8\gems\activesupport-2.3.5\lib\active_support\core_ext\object\blank.rb). The key bits are as follows:
class NilClass
def blank?
true
end
end
class String
def blank?
self !~ /\S/
end
end