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 ...

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.