Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simplest way to check for just spaces in ruby

Tags:

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?

like image 690
user301752 Avatar asked Mar 25 '10 18:03

user301752


People also ask

How do you check whitespace in Ruby?

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.

How do you check if a string is just spaces?

To check if a string contains only spaces, call the trim() method on the string and check if the length of the result is equal to 0 . If the string has a length of 0 after calling the trim method, then the string contains only spaces.

What does .strip do in Ruby?

The . strip method removes the leading and trailing whitespace on strings, including tabs, newlines, and carriage returns ( \t , \n , \r ).

What is whitespace in Ruby?

Whitespace characters such as spaces and tabs are generally ignored in Ruby code, except when they appear in strings. Sometimes, however, they are used to interpret ambiguous statements. Interpretations of this sort produce warnings when the -w option is enabled.


1 Answers

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.

like image 105
MikeJ Avatar answered Sep 18 '22 16:09

MikeJ