Using over 9 unnamed entries in Ruby Regex

I have a long string formatted as a journal entry, and I want to get a few snapshots from it and save them in different variables.

I know that Ruby stores the first 9 captures in $ 1 ... $ 9 variables, does it also save other entries in $ 10 ... $ 99?

If there wasn’t an easy way to do this?

+4
source share
2 answers

Yes it is.

"a2c4d7l4l0j4h9h7".gsub(/(\w)(\d)(\w)(\d)(\w)(\d)(\w)(\d)(\w)(\d)(\w)(\d)(\w)(\d)(\w)(\d)/) do $12 end #=> "4" 
+6
source

String#match returns a MatchData object that contains an array of captures.

 m = Regexp.new('(.)' * 20).match('The quick brown fox jumps over the lazy dog') m[12] # => "r" 

Although $ 12 also works:

 > $12 # => "r" 
+8
source

Source: https://habr.com/ru/post/1441116/


All Articles