Reputation: 275
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?
Upvotes: 22
Views: 21909
Reputation: 1631
s.include?(" ")
Examples:
s = "A B C D"
s.include?(" ") #=> true
s = "ABCD"
s.include?(" ") #=> false
Upvotes: 0
Reputation: 67832
s =~ /\A\s*\Z/
Regex solution. Here's a short ruby regex tutorial.
Upvotes: 16
Reputation: 1162
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 get it from the activesupport
gem. Install with gem install activesupport
. In your file either require 'active_support/core_ext
to get all active support extensions to the base classes, or require 'active_support/core_ext/string'
to get just the extensions to the String
class. Either way, the blank?
method will be available after the require.
Upvotes: 36
Reputation: 1833
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
Upvotes: 6
Reputation: 11907
"best" depends on the context, but here is a simple way.
some_string.strip.empty?
Upvotes: 30
Reputation: 199234
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
>>
Upvotes: 0