Skip to content

Instantly share code, notes, and snippets.

@estum
Created February 23, 2015 20:43
Show Gist options
  • Save estum/8d2f3da8fc84d03dfb5a to your computer and use it in GitHub Desktop.
Save estum/8d2f3da8fc84d03dfb5a to your computer and use it in GitHub Desktop.
MatchData#named_captures: a hash of names and matches of captures
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