Ruby 2.4 MatchData#values_at

Rohit Kumar

Rohit Kumar

December 21, 2016

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

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.