The match operator =~ helps you check if a piece of text fits a pattern. It tells you where the pattern starts or if it is not found.
0
0
Match operator (=~) in Ruby
Introduction
When you want to find if a word or phrase exists inside a longer text.
When you need to check if a text follows a certain format, like an email or phone number.
When you want to split or process text based on patterns.
When you want to quickly test if a string contains certain characters or sequences.
Syntax
Ruby
string =~ /pattern/
The =~ operator returns the index where the pattern starts in the string.
If the pattern is not found, it returns nil.
Examples
This checks if "ll" is in "hello". It returns 2 because "ll" starts at index 2.
Ruby
"hello" =~ /ll/This looks for "z" in "world" but does not find it, so it returns nil.
Ruby
"world" =~ /z/This finds digits at the start of the string and returns 0 because digits start at index 0.
Ruby
"123abc" =~ /\d+/Sample Program
This program checks if the word "Ruby" is in the text. It prints where it starts or says it is not found.
Ruby
text = "I love Ruby programming" pattern = /Ruby/ result = text =~ pattern if result puts "Pattern found at index #{result}" else puts "Pattern not found" end
OutputSuccess
Important Notes
The match operator works with regular expressions, which are patterns to find text.
Remember that the index starts at 0, so the first character is position 0.
If you only want to check if a pattern exists, you can test if the result is not nil.
Summary
The =~ operator checks if a pattern is in a string and returns the start index.
It returns nil if the pattern is not found.
Use it to quickly find or test text patterns in Ruby.