How to check if a named group exists in a MatchData object?
ruby-1.9.2-p180 :003 > result = "test string".match(/(?<mtch>test)/) => #<MatchData "test" mtch:"test"> ruby-1.9.2-p180 :011 > result["mtch"] => "test" ruby-1.9.2-p180 :012 > result["fail"] IndexError: undefined group name reference: fail from (irb):12:in `[]' from (irb):12 from /Users/jeremysmith/.rvm/rubies/ruby-1.9.2-p180/bin/irb:16:in `<main>' There is no MatchData function to check for the existence of a named group. is there any other way to check?
result.names.include? 'mtch' # => true result.names.include? 'fail' # => false result["fail"] rescue false - one easy way. There are more elegant ways, but the rescue modifier is often useful, it is simple if you do not want to pay attention to excepted exceptions.
Just check if the data matches with p . In your case, the example already shows what you have.
=> #<MatchData "test" mtch:"test"> This means that the entire line that matches is equal to "test" , and the inventory of the name is (only) mtch . If he has a different name, it will be included in this form.