Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this ruby code compare regex?

Tags:

ruby

if string == /\s{1,}/ or string == /\n{1,}/
  puts "emptiness..."
end
like image 653
gagagag Avatar asked Nov 27 '22 03:11

gagagag


1 Answers

To test a String against a 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 case statements):

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

Note: String#=== doesn't do what you want:

' ' === /\s{1,}/      # => false
'f' === /\s{1,}/      # => false
like image 108
James A. Rosen Avatar answered Dec 19 '22 07:12

James A. Rosen