Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

See if a ruby string has whitespace in it

Tags:

string

ruby

I want to see if a string has any white space in it. What's the most effective way of doing this in ruby?

Thanks

like image 574
Splashlin Avatar asked Jan 25 '10 06:01

Splashlin


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 for whitespace in a string?

For checking if a string contains whitespace use a Matcher and call its find method. Show activity on this post. Character. isWhitespace(char)

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 by "white space" you mean in the Regular Expression sense, which is any of space character, tab, newline, carriage return or (I think) form-feed, then any of the answers provided will work:

s.match(/\s/) s.index(/\s/) s =~ /\s/ 

or even (not previously mentioned)

s[/\s/] 

If you're only interested in checking for a space character, then try your preference of

s.match(" ") s.index(" ") s =~ / / s[" "] 

From irb (Ruby 1.8.6):

s = "a b" puts s.match(/\s/) ? "yes" : "no" #-> yes puts s.index(/\s/) ? "yes" : "no" #-> yes puts s =~ /\s/ ? "yes" : "no" #-> yes puts s[/\s/] ? "yes" : "no" #-> yes  s = "abc" puts s.match(/\s/) ? "yes" : "no" #-> no puts s.index(/\s/) ? "yes" : "no" #-> no puts s =~ /\s/ ? "yes" : "no" #-> no puts s[/\s/] ? "yes" : "no" #-> no 
like image 71
Mike Woodhouse Avatar answered Sep 21 '22 21:09

Mike Woodhouse