I want to name the capture of string that I get from scan. How to do it?
\"555-333-7777\".scan(/(\\d{3})-(\\d{3})-(\\d{4})/).flatten #=> [\"555\", \"333\", \"
A way to turn capture group names and their values into a hash is to use a regex with named captures using (?
and then access the %~
global "last match" variable.
regex_with_named_capture_groups = %r'(?\d{3})-(?\d{3})-(?\d{4})'
"555-333-7777"[regex_with_named_capture_groups]
match_hash = $~.names.inject({}){|mem, capture| mem[capture] = $~[capture]; mem}
# => {"area"=>"555", "city"=>"333", "local"=>"7777"}
# If ActiveSupport is available
match_hash.symbolize_keys!
# => {area: "555", city: "333", local: "7777"}