We write about Ruby on Rails, React.js, React Native, remote work, open source, engineering and design.
We can use MatchData#[]
to extract named capture and positional capture
groups.
1
2pattern=/(?<number>\d+) (?<word>\w+)/
3pattern.match('100 thousand')[:number]
4#=> "100"
5
6pattern=/(\d+) (\w+)/
7pattern.match('100 thousand')[2]
8#=> "thousand"
9
Positional capture groups could also be extracted using MatchData#values_at
.
1
2pattern=/(\d+) (\w+)/
3pattern.match('100 thousand').values_at(2)
4#=> ["thousand"]
5
In Ruby 2.4, we can pass string or symbol to extract named capture groups
to method #values_at
.
1
2pattern=/(?<number>\d+) (?<word>\w+)/
3pattern.match('100 thousand').values_at(:number)
4#=> ["100"]
5