开发者

See if a ruby string has whitespace in it

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

Thanks


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


some_string.match(/\s/)


"text message".include?(' ') #=> true
"text_message".include?(' ') #=> false


It is usually done like this:

str =~ /\s/

You can read about regular expressions here.


you can use index

"mystring".index(/\s/)


I really enjoy using count for this.

"hello 1".count("")   #=> 0
"hello 1".count(" ")  #=> 1
" hello 1".count(" ") #=> 2


"hello 1".count(" ") > 0 #=> true
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜