Prematch and Postmatch

The MatchData class supplies the pre_match and post_match methods to return the strings preceding or following a match. Here, for example, I am making a match on the comment character, #:

pre_post_match.rb

x = /#/.match( 'def myMethod # This is a very nice method' )
puts( x.pre_match )        #=> def myMethod
puts( x.post_match )       #=>  This is a very nice method

Alternatively, you can use the special variables, $` (with a backquote) and $' (with a normal quote), to access pre- and postmatches, respectively:

x = /#/.match( 'def myMethod # This is a very nice method' )
puts( $` )                 #=> def myMethod
puts( $' )                 #=>  This is a very nice method

When using match with groups, you can use array-style indexing to obtain specific items. Index 0 is the original string; higher indexes are the groups:

match_groups.rb

puts( /(.)(.)(.)/.match("abc")[2] )                 #=> "b"

You can use the special variable to access the last MatchData object, and once again you can refer to groups using array-style indexing:

puts( $˜[0], $˜[1], $˜[3] )

However, to use the full range of methods of the Array class, you must use to_a or captures to return the match groups as an array:

puts( $˜.sort )               # this doesn't work!
puts( $˜.captures.sort )      # this does
..................Content has been hidden....................

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