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?
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.
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.
The . strip method removes the leading and trailing whitespace on strings, including tabs, newlines, and carriage returns ( \t , \n , \r ).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With