Why doesn't this ruby ​​code compare regular expression?

if string == /\s{1,}/ or string == /\n{1,}/
  puts "emptiness..."
end
+3
source share
2 answers

To test a Stringon Regex, you can do any of five things:

1: use String#match:

' '.match /\s{1,}/    # => #<MatchData:0x118ca58>
'f'.match /\s{1,}/    # => nil

2: Use Regex#match:

/\s{1,}/.match ' '    # => <MatchData:0x11857e4>
/\s{1,}/.match 'f'    # => nil

3: Use String#=~:

' ' =~ /\s{1,}/       # => 0
'f' =~ /\s{1,}/       # => nil

4: Use Regex#=~:

/\s{1,}/ =~ ' '       # => 0
/\s{1,}/ =~ 'f'       # => nil

5: Use Regex#===(this is what is used in statements case):

/\s{1,}/ === ' '      # => true
/\s{1,}/ === 'f'      # => false

Note: String#=== does not execute :

' ' === /\s{1,}/      # => false
'f' === /\s{1,}/      # => false
+22
source

When comparing with regular expressions in Ruby, you should use the comparison "= ~" instead of "==".

Try it and see if it gives you what you expect.

+6
source

Source: https://habr.com/ru/post/1734826/


All Articles