December 21, 2016
This blog is part of our Ruby 2.4 series.
We can use MatchData#[]
to extract named capture and positional capture
groups.
pattern=/(?<number>\d+) (?<word>\w+)/
pattern.match('100 thousand')[:number]
#=> "100"
pattern=/(\d+) (\w+)/
pattern.match('100 thousand')[2]
#=> "thousand"
Positional capture groups could also be extracted using MatchData#values_at
.
pattern=/(\d+) (\w+)/
pattern.match('100 thousand').values_at(2)
#=> ["thousand"]
In Ruby 2.4, we can pass string or symbol to extract named capture groups to
method #values_at
.
pattern=/(?<number>\d+) (?<word>\w+)/
pattern.match('100 thousand').values_at(:number)
#=> ["100"]
If this blog was helpful, check out our full blog archive.