0

Answer from How do I get the match data for all occurrences of a Ruby regular expression in a string?:

input = "abc12def34ghijklmno567pqrs"
numbers = /\d+/
input.gsub(numbers) { |m| p $~ }

Result is as requested:

⇒ #<MatchData "12">
⇒ #<MatchData "34">
⇒ #<MatchData "567">

Would someone break down what the answerer is doing in input.gsub(numbers) { |m| p $~ }?

Also, how would I access each of the MatchDatas?

Community
  • 1
  • 1

1 Answers1

4

Since I’m the answerer, I would try to explain.

$~ is one of Ruby predefined globals. It returns the MatchData from the previous successful pattern match. It may be accessed using Regexp.last_match as well.

As stated in the documentation, gsub with block is commonly used to modify string, but here we use the fact it calls the codeblock on every match. Block variable m there is a simple string for that match, so whether we need the whole MatchData instance, we should use the predefined global $~. In the mentioned example we simple print each MatchData with p $~.

The trick here is that $~ returns the last MatchData. So, everything you need is to use $~ variable despite it’s repulsive look. Or, you might set:

my_beauty_name_match_data_var = $~

and play with the latter. Hope it helps.

Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
  • also, you can use predefined variable `$&` to get the string for match and pass nothing to block(I mean instead of `m`) – Rustam Gasanov Dec 24 '14 at 06:39
  • Thank you! That's amazing that you were able to find my question about your code so quickly! Would you link to your explanation here from your answer here (http://stackoverflow.com/questions/6804557/how-do-i-get-the-match-data-for-all-occurrences-of-a-ruby-regular-expression-in/14662414#14662414)? – user4390735 Dec 24 '14 at 06:40
  • Glad to help. Linked. – Aleksei Matiushkin Dec 24 '14 at 06:44