O'Reilly logo

Sams Teach Yourself Ruby in 21 Days by Mark Slagell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required