---
title: "Ruby 3.1 adds MatchData#match & MatchData#match_length"
description: "Ruby 3.1 adds MatchData#match & MatchData#match_length"
canonical_url: "https://www.bigbinary.com/blog/ruby-3-1-adds-match-data-methods"
markdown_url: "https://www.bigbinary.com/blog/ruby-3-1-adds-match-data-methods.md"
---

# Ruby 3.1 adds MatchData#match & MatchData#match_length

Ruby 3.1 adds MatchData#match & MatchData#match_length

- Author: Ashik Salman
- Published: November 9, 2021
- Categories: Ruby 3.1, Ruby

Ruby 3.1 introduces the `MatchData#match` & `MatchData#match_length` methods
which returns the substring matched against a regular expression & it's length
respectively.

```ruby
=> str = "Ruby 3.1 introduces MatchData#match method"
=>  m = /(?<lang>\S+)(\s)(?<version>[\d\.]+)/.match(str)
=> #<MatchData "Ruby 3.1" lang:"Ruby" version:"3.1">
```

### Before Ruby 3.1

We have `MatchData#[]` method to access all the substring groups that are
matched. We can access either a single match or multiple matches by giving a
single index or a range of indexes, respectively, using `MatchData#[]` method.

```ruby
=> m[:lang]
=> "Ruby"

=> m[1]
=> "Ruby"
=> m[:version]
=> "3.1"

=> m[0..2]
=> ["Ruby 3.1", "Ruby", "3.1"]

=> m[1..2]
=> ["Ruby", "3.1"]


=> m[0].length
=> 8
```

### After Ruby 3.1

We have two new methods now to access the match data & its length. The
`MatchData#match` & `MatchData#match_length` methods accepts either an index or
a symbol as an argument to return the match data & its length.

```ruby
=> m.match(0)
=> "Ruby 3.1"

=> m.match(:version)
=> "3.1"

=> m.match(3)
=> nil

=> m.match_length(0)
=> 8

=> m.match_length(:version)
=> 3

=> m.match_length(3)
=> nil
```

Please note that `MatchData#match` is not same as `MatchData#[]` method. The
later accepts an optional length or range as an argument to return the matched
data but the former doesn't accept it, instead it allows only a single index or
symbol as an argument.

Here's the relevant [pull request](https://github.com/ruby/ruby/pull/4851) and
[feature discussion](https://bugs.ruby-lang.org/issues/18172) for this change.

## Links

- [Human page](https://www.bigbinary.com/blog/ruby-3-1-adds-match-data-methods)
