Regexes and Matches as Objects

The work we've been doing today has not looked much like object-oriented code. That's a bow to convention and history. Almost all scripts using regular expressions have been written in this highly condensed and cryptic style, and if Ruby is to allow programmers to keep using the regular expression skills they've accumulated over the years, there isn't much that can be done to help with readability. But there is at least one situation when a more modern, OO layout might be advantageous.

There is only one of each of the variables $`, $&, $', $1, $2, and so forth. These hold information about the most recent regex match, so a new match wipes out the old values. Instead, the same information can be encapsulated in a ...

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.