user301752
user301752

Reputation: 275

simplest way to check for just spaces in ruby

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

Answers (8)

Breen ho
Breen ho

Reputation: 1631

s.include?(" ")

Examples:

s = "A B C D"
s.include?(" ") #=> true

s = "ABCD"
s.include?(" ") #=> false

Upvotes: 0

Stefan Kendall
Stefan Kendall

Reputation: 67832

s =~ /\A\s*\Z/

Regex solution. Here's a short ruby regex tutorial.

Upvotes: 16

MikeJ
MikeJ

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

Levi
Levi

Reputation: 4658

Yet another :) string.all? { |c| c == ' ' }

Upvotes: -1

miorel
miorel

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

jshen
jshen

Reputation: 11907

"best" depends on the context, but here is a simple way.

some_string.strip.empty?

Upvotes: 30

OscarRyz
OscarRyz

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

Beanish
Beanish

Reputation: 1662

a = "  " 

a.each_byte do |x|
  if x == 32
    puts "space"
  end
end

Upvotes: 0

Related Questions