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?

Answers


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

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


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.


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

some_string.strip.empty?

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

a = "  " 

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

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
>> 

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


Need Your Help

oracle error, column not allowed here

oracle ora-00984

I haven't used Oracle for a while so I'm a bit rusty.

Can I manually navigate with turbolinks in Rails?

ruby-on-rails pjax turbolinks

I have an html table with rows and a jQuery handler on click.