【发布时间】:2016-04-12 08:28:01
【问题描述】:
我在较长的脚本中使用它,但一个简短的示例将说明我遇到的问题类型。
my_array2 = ["help", "not", "too"]
my_array2.each do |element|
element.sub!(/(\w{1})(\w+)/,"\\1")
end
# this gives me the expected ['h','n','t']
如果我这样做
my_array2 = ["help", "not", "too"]
my_array2.each do |element|
element.sub!(/(\w{1})(\w+)/, $1)
end
# this gives me ['t','h','n'] (instead of ['h','n','t'] as expected).
发生了什么事?当我使用 $1 返回第一个正则表达式捕获组时,为什么会得到一个“移位”的结果?
【问题讨论】:
-
您必须使用块形式,即
sub!(/.../) { $1 }。否则,$1 指的是上一场比赛。 -
间接答案是:在Ruby中变量是按值传递的。
$1在您的sub!调用之前 的值是传递给sub!的值,而不是对$1的引用,它最终将填充到sub!调用中。跨度>