MatchData

The operator is not the only means of finding a match. The Regexp class also has a match method. This works in similar way to , but when a match is made, it returns a MatchData object rather than an integer. A MatchData object contains the result of a pattern match. At first sight, this may appear to be a string.

match.rb

puts( /cde/ =˜ 'abcdefg' )        #=> 2
puts( /cde/.match('abcdefg') )    #=> cde

In fact, it is an instance of the MatchData class that contains a string:

p( /cde/.match('abcdefg') )       #=> #<MatchData: "cde" >

A MatchData object may contain groups, or captures, and these can be returned in an array using either the to_a or captures method, like this:

matchdata.rb

x = /(^.*)(#)(.*)/.match( 'def myMethod # This is a very nice method' ...

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.