查看ruby字符串中是否有空格

Spl*_*lin 23 ruby string

我想看看字符串中是否有任何空格.在红宝石中这样做最有效的方法是什么?

谢谢

Mik*_*use 38

如果用"空格"表示正则表达式意义,即空格字符,制表符,换行符,回车符或(我认为)换页符,则提供的任何答案都可以使用:

s.match(/\s/)
s.index(/\s/)
s =~ /\s/
Run Code Online (Sandbox Code Playgroud)

甚至(以前未提及)

s[/\s/]
Run Code Online (Sandbox Code Playgroud)

如果您只想检查空格字符,请尝试您的偏好

s.match(" ")
s.index(" ")
s =~ / /
s[" "]
Run Code Online (Sandbox Code Playgroud)

来自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
Run Code Online (Sandbox Code Playgroud)

  • 更新后,[String#match?](http://ruby-doc.org/core-2.4.1/String.html#method-i-match-3F) 在 Ruby v2 中首次亮相。 4、所以现在也可以写`s.match?(/\s/)`。 (2认同)

小智 7

"text message".include?(' ') #=> true
"text_message".include?(' ') #=> false
Run Code Online (Sandbox Code Playgroud)