Use Pattern Matching Operator in Ruby
Nurudeen Ibrahim Feb 23, 2022
Checking any data against other data is known as pattern matching. The article discusses Ruby’s basic pattern matching operator (
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
String define this operator the same way, so the order of the two does not matter.
p "David is a boy" =~ /boy/ p /boy/ =~ 'David is a boy' p 'David is a boy' =~ /boy/ p /boy/ =~ 'David is a boy'
11 11 11 11
If there’s no match,
nil is returned instead.
p "David is a boy" =~ /girl/ p /girl/ =~ 'David is a boy'