Ruby 3.1 adds MatchData#match & MatchData#match_length

Ashik Salman

Ashik Salman

November 9, 2021

This blog is part of our  Ruby 3.1 series.

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

=> 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 which are matched. We can access either a single match or multiple matches by giving a single index or range of indexes respectively using MatchData#[] method.

=> 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 & it's length. The MatchData#match & MatchData#match_length methods accepts either an index or a symbol as an argument to return the match data & it's length.

=> 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 argument.

Here's the relevant pull request and feature discussion for this change.

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.