Convert named matches in MatchData to Hash

后端 未结 5 1478
抹茶落季
抹茶落季 2021-02-12 13:45

I have a rather simple regexp, but I wanted to use named regular expressions to make it cleaner and then iterate over results.

Testing string:

testing_s         


        
5条回答
  •  迷失自我
    2021-02-12 14:03

    If you need a full Hash:

    captures = Hash[ dimensions.names.zip( dimensions.captures ) ]
    p captures
    #=> {"width"=>"111", "height"=>"222", "depth"=>"333"}
    

    If you just want to iterate over the name/value pairs:

    dimensions.names.each do |name|
      value = dimensions[name]
      puts "%6s -> %s" % [ name, value ]
    end
    #=>  width -> 111
    #=> height -> 222
    #=>  depth -> 333
    

    Alternatives:

    dimensions.names.zip( dimensions.captures ).each do |name,value|
      # ...
    end
    
    [ dimensions.names, dimensions.captures ].transpose.each do |name,value|
      # ...
    end
    
    dimensions.names.each.with_index do |name,i|
      value = dimensions.captures[i]
      # ...
    end
    

提交回复
热议问题