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\", \"
You should use match
with named captures, not scan
m = "555-333-7777".match(/(?\d{3})-(?\d{3})-(?\d{4})/)
m # => #
m[:area] # => "555"
m[:city] # => "333"
If you want an actual hash, you can use something like this:
m.names.zip(m.captures).to_h # => {"area"=>"555", "city"=>"333", "number"=>"7777"}
Or this (ruby 2.4 or later)
m.named_captures # => {"area"=>"555", "city"=>"333", "number"=>"7777"}