input.gsub(numbers){| m | p $〜}在Ruby中匹配字符串中所有出现的数据 [英] input.gsub(numbers) { |m| p $~ } Matching data in Ruby for all occurrences in a string

查看:66
本文介绍了input.gsub(numbers){| m | p $〜}在Ruby中匹配字符串中所有出现的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

结果是按要求的:

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

有人会弄清答题者在input.gsub(numbers) { |m| p $~ }中的工作吗?

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

此外,我将如何访问每个MatchData?

Also, how would I access each of the MatchDatas?

推荐答案

由于我是回答者,所以我会尽力解释.

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

$~ Ruby预定义全局变量之一.它从上一次成功的模式匹配中返回 MatchData .也可以使用Regexp.last_match进行访问.

$~ 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.

如文档中所述 中所述,带块的gsub通常用于修改字符串,但是在这里我们使用它在每次匹配时都调用代码块的事实.块变量m有一个用于该匹配的简单字符串,因此,无论我们是否需要整个MatchData实例,都应使用预定义的全局$~.在上述示例中,我们简单地用p $~打印每个MatchData.

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 $~.

这里的窍门是$~返回最后一个MatchData .因此,尽管外观令人反感,您所需要的只是使用$~变量.或者,您可以设置:

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.

这篇关于input.gsub(numbers){| m | p $〜}在Ruby中匹配字符串中所有出现的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆