MatchData

From RubySpec

Jump to: navigation, search

According to Programming Ruby, 1st edition "MatchData is the type of the special variable $~, and is the type of the object returned by Regexp#match and Regexp#last_match. It encapsulates all the results of a pattern match, results normally accessed through the special variables $&, $', $`, $1, $2, and so on."

Example:

 irb(main):002:0> str = "Hello242424World"
 => "Hello242424World"
 irb(main):003:0> re = Regexp.new(/[a-z]+/)
 => /[a-z]+/
 irb(main):004:0> md = re.match(str)
 => #<MatchData:0x2df86b0>
 irb(main):005:0> md.pre_match
 => "H"
 irb(main):006:0> md.post_match
 => "242424World"
 irb(main):007:0> md[0]
 => "ello"
Personal tools