simplest way to check for just spaces in ruby

user301752 picture user301752 · Mar 25, 2010 · Viewed 17.2k times · Source

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?

Answer

MikeJ picture MikeJ · Mar 25, 2010

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.