String Methods

Up to now, I’ve used methods of the Regexp class when processing strings. In fact, pattern matching can go both ways because the String class has a few regular expression methods of its own. These include and match (so you can switch the order of the String and Regexp objects when matching), plus the scan method that iterates through a string looking for as many matches as possible. Each match is added to an array. Here, for example, I am looking for matches on the letters a, b, or c. The match method returns the first match (“a”) wrapped up in a MatchData object, but the scan method keeps scanning along the string and returns all the matches it finds as elements in an array:

match_scan.rb

TESTSTR = "abc is not cba" puts( "\n--match--" ...

Get The Book of 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.