Convert named matches in MatchData to Hash

Viewed 7672

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_string = "111x222b333"

My regexp:

regexp = %r{
                (?<width> [0-9]{3} ) {0}
                (?<height> [0-9]{3} ) {0}
                (?<depth> [0-9]+ ) {0}

                \g<width>x\g<height>b\g<depth>
            }x
dimensions = regexp.match(testing_string)

This work like a charm, but heres where the problem comes:

dimensions.each { |k, v| dimensions[k] = my_operation(v) }

# ERROR !

 undefined method `each' for #<MatchData "111x222b333" width:"111" height:"222" depth:"333">.

There is no .each method in MatchData object, and I really don't want to monkey patch it.

How can I fix this problem ?

I wasn't as clear as I thought: the point is to keep names and hash-like structure.

5 Answers
Related