Created
February 23, 2015 20:43
-
-
Save estum/8d2f3da8fc84d03dfb5a to your computer and use it in GitHub Desktop.
MatchData#named_captures: a hash of names and matches of captures
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "active_support/core_ext/hash/transform_values" | |
class MatchData | |
# Returns a hash containing the names and matches of captures or nil. | |
# | |
# A key of the hash is a name of the named captures. A value of the hash is a | |
# matched string or an array of corresponding matches. | |
# | |
# puts /(?<foo>.)(?<bar>.)(?<baz>.)(?<baz>.)/.match("hoge", &:named_captures).inspect | |
# # => {"foo"=>"h", "bar"=>"o", "baz"=>["g", "e"]} | |
def named_captures | |
regexp.named_captures.transform_values! do |indicies| | |
if indicies.one? | |
self[*indicies] | |
else | |
values_at(*indicies) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment