---
title: "Ruby 2.4 Extracting captured data from Regexp results"
description:
  "Ruby 2.4 adds support for extracting named captures and positional capture
  groups from Regexp match results"
canonical_url: "https://www.bigbinary.com/blog/ruby-2-4-adds-better-support-for-extracting-captured-data-from-regexp-match-results"
markdown_url: "https://www.bigbinary.com/blog/ruby-2-4-adds-better-support-for-extracting-captured-data-from-regexp-match-results.md"
---

# Ruby 2.4 Extracting captured data from Regexp results

Ruby 2.4 adds support for extracting named captures and positional capture
groups from Regexp match results

- Author: Rohit Kumar
- Published: November 10, 2016
- Categories: Ruby 2.4, Ruby

Ruby has [MatchData](https://ruby-doc.org/core-2.2.0/MatchData.html) type which
is returned by `Regexp#match` and `Regexp.last_match`.

It has methods `#names` and `#captures` to return the names used for capturing
and the actual captured data respectively.

```ruby

pattern = /(?<number>\d+) (?<word>\w+)/
match_data = pattern.match('100 thousand')
#=> #<MatchData "100 thousand" number:"100" word:"thousand">

>> match_data.names
=> ["number", "word"]
>> match_data.captures
=> ["100", "thousand"]

```

If we want all named captures in a key value pair, we have to combine the result
of names and captures.

```ruby

match_data.names.zip(match_data.captures).to_h
#=> {"number"=>"100", "word"=>"thousand"}

```

Ruby 2.4 adds [`#named_captures`](https://bugs.ruby-lang.org/issues/11999) which
returns both the name and data of the capture groups.

```ruby

pattern=/(?<number>\d+) (?<word>\w+)/
match_data = pattern.match('100 thousand')

match_data.named_captures
#=> {"number"=>"100", "word"=>"thousand"}

```

## Links

- [Human page](https://www.bigbinary.com/blog/ruby-2-4-adds-better-support-for-extracting-captured-data-from-regexp-match-results)
