3
if string == /\s{1,}/ or string == /\n{1,}/
puts "emptiness..."
end
if string == /\s{1,}/ or string == /\n{1,}/
puts "emptiness..."
end
當與Ruby中的正則表達式比較時,應該使用'=〜'比較而不是'=='。
嘗試一下,看看它是否給你你所期望的。
要測試String
針對Regex
,你可以做任何的五兩件事:
1:使用String#match
:
' '.match /\s{1,}/ # => #<MatchData:0x118ca58>
'f'.match /\s{1,}/ # => nil
2:使用Regex#match
:
/\s{1,}/.match ' ' # => <MatchData:0x11857e4>
/\s{1,}/.match 'f' # => nil
3:使用String#=~
:
' ' =~ /\s{1,}/ # => 0
'f' =~ /\s{1,}/ # => nil
4:使用Regex#=~
:
/\s{1,}/ =~ ' ' # => 0
/\s{1,}/ =~ 'f' # => nil
5:使用Regex#===
(這是在case
語句中使用):
/\s{1,}/ === ' ' # => true
/\s{1,}/ === 'f' # => false
注:String#===
不做你想做的:
' ' === /\s{1,}/ # => false
'f' === /\s{1,}/ # => false