Some Container Methods That Use Regexes

We've only looked at the =~ and !~ methods as applied to a regex receiver with a string argument. For convenience, the order can be reversed; the receiver can be a string and the argument a regex, and the results are the same.

"Nobody knows the trouble I've seen" =~ /\bt/  #-> 13

You can even have strings for both receiver and argument, but in that case Ruby will convert the argument to a regex before testing.

Back on Day 3 you got a glimpse of the Array#grep method. The example given there showed only simple substring matching, but now that you know more about regular expressions, you can probably think of more interesting things to do with grep. How about finding the methods that can be applied to an ...

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.