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

MatchData#to_a

mtch.to_a → anArray

Returns the array of matches.

Example
m = /(.)(.)(\d+)(\d)/.match("THX1138.")
m.to_a   #=> ["HX1138", "H", "X", "113", "8"]

Because to_a is called when expanding *variable, there’s a useful assignment shortcut for extracting matched fields. This is slightly slower than accessing the fields directly (as an intermediate array is generated).

Example
all,f1,f2,f3 = * /(.)(.)(\d+)(\d)/.match("THX1138.")
all   #=> "HX1138"
f1    #=> "H"
f2    #=> "X"
f3    #=> "113"
See also #string #to_s #size #values_at also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0