input.gsub(numbers) { |m| p $~ } Matching data in Ruby for all occurrences in a string

安稳与你 提交于 2019-12-14 03:04:28

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/27632395/input-gsubnumbers-m-p-matching-data-in-ruby-for-all-occurrences-in-a

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!