Convert named matches in MatchData to Hash

后端 未结 5 1483
抹茶落季
抹茶落季 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:00

    I'd attack the whole problem of creating the hash a bit differently:

    irb(main):052:0> testing_string = "111x222b333"
    "111x222b333"
    irb(main):053:0> hash = Hash[%w[width height depth].zip(testing_string.scan(/\d+/))]
    {
        "width" => "111",
        "height" => "222",
        "depth" => "333"
    }
    

    While regex are powerful, their siren-call can be too alluring, and we get sucked into trying to use them when there are more simple, or straightforward, ways of accomplishing something. It's just something to think about.


    To keep track of the number of elements scanned, per the OPs comment:

    hash = Hash[%w[width height depth].zip(scan_result = testing_string.scan(/\d+/))]
    => {"width"=>"111", "height"=>"222", "depth"=>"333"}
    scan_result.size
    => 3
    

    Also hash.size will return that, as would the size of the array containing the keys, etc.

提交回复
热议问题