How to Use Pattern Matching Operator in Ruby
Nurudeen Ibrahim
Feb 02, 2024
Checking any data against other data is known as pattern matching. The article discusses Ruby’s basic pattern matching operator (=~
) briefly.
Pattern Matching Operator (=~
) in Ruby
The pattern matching operator (=~
) matches a regular expression against a string. The operator (=~
) returns the offset if the string meets the expression and returns nil
otherwise.
Regexp
and String
define this operator the same way, so the order of the two does not matter.
Example Code:
p 'David is a boy' =~ /boy/
p(/boy/ =~ 'David is a boy')
p 'David is a boy' =~ /boy/
p(/boy/ =~ 'David is a boy')
Output:
11
11
11
11
If there’s no match, nil
is returned instead.
Example Code:
p 'David is a boy' =~ /girl/
p(/girl/ =~ 'David is a boy')
Output:
nil
nil