Back to Blog

Ruby 2.4 MatchData#values_at

on 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.

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

Changes in Ruby 2.4

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

You might also like

If you liked this blog post, check out similar ones from BigBinary