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' )
x.captures.each{ |item| puts( item ) }

The previous displays the following:

def myMethod
#
 This is a very nice method

Note that there is a subtle difference between the captures and to_a methods. The first returns only the captures:

x.captures    #=>["def myMethod ","#"," This is a very nice method"]

The second returns the original string (at index 0) followed by the captures:

x.to_a    #=>["def myMethod # This is a very nice method","def myMethod
","#"," This is a very nice method"]
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.138.104