How to do named capture in ruby

前端 未结 3 1281
無奈伤痛
無奈伤痛 2021-02-04 23:28

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\", \"         


        
3条回答
  •  春和景丽
    2021-02-05 00:29

    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"}
    

提交回复
热议问题