Matching Against Patterns
If we want to check whether two strings are identical, we can of course use the equality operator:
| if "something else" == "something" |
| # we'll never get here |
| end |
To check whether a string matches a regular expression, Ruby offers the =~ operator. Some people call it the “matches” operator, or the “is like” operator. If the string matches the pattern defined in the regular expression, it returns a truthy value, which means we can use it in an if check. If we wanted to check whether a URL was an https one rather than http, we could use =~:
| url = "https://example.com/" |
| |
| if url =~ /\Ahttps:/ |
| puts "The URL is https" |
| else |
| puts "The URL is not https" |
| end |
We can also use the match method ...
Get Text Processing with Ruby now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.