This blog is part of our Ruby 2.4 series.

Ruby 2.3

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"]

Changes in Ruby 2.4

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"]