Simple Pattern Matching
There is a class for regular expressions (Regexp) and a “matching” operator (=~). To express a regex literal, we usually surround it with forward slashes. The simplest regular expressions are treated just like substrings.
re = /tuv/ re.type #-> Regexp re =~ "rstuvwx" #-> 2 re =~ "Tavern" #-> nil
Note
The forward slashes are traditional. Just as with string literals, you can specify some other delimiter; start with %r to make it clear that you want a regular expression. %r[xyz] is the same as /xyz/.
"tuv" is a substring of "rstuvwx" and not "Tavern". Why do we get 2 and nil instead of true and false? Remember, anything other than nil or false is considered true, so we can use these to make yes/no decisions as if they ...
Get Sams Teach Yourself Ruby in 21 Days 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.