How to do named capture in ruby

前端 未结 3 1267
無奈伤痛
無奈伤痛 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:30

    Something like this?

    "555-333-7777" =~ /^(?\d+)\-(?\d+)\-(?\d+)$/
    Hash[$~.names.collect{|x| [x.to_sym, $~[x]]}]
     => {:area=>"555", :city=>"333", :local=>"7777"}
    

    Bonus version:

    Hash[[:area, :city, :local].zip("555-333-7777".split("-"))]
    => {:area=>"555", :city=>"333", :local=>"7777"}
    

提交回复
热议问题