Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method · added in Ruby 3.1

MatchData#match_length

mtch.match_length(n) → array

Returns the length of the captured substring corresponding to the argument. n can be a string or symbol to reference a named capture.

Example
m = /(.)(.)(\d+)(\d)(\w)?/.match("THX1138.")
m.match_length(0)       #=> 6
m.match_length(4)       #=> 1
m.match_length(5)       #=> nil

m = /(?<foo>.)(.)(?<bar>.+)/.match("hoge")
m.match_length(:foo)    #=> 1
m.match_length(:bar)    #=> 2

Ruby version changes

  1. 3.1
See also #match #named_captures #length #names also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2