gsub 缓存组?

gsub caching groups?

如果我运行这个代码:

"Retailer Staff .60".gsub(/.*$(\d+(\.\d+)?).*/, )
# => 5.60

然后我将值更改为:

"Retailer Staff ".gsub(/.*$(\d+(\.\d+)?).*/, )
# => 5.60

答案停留在5.60。然后,如果我再次 运行 同一行,我会得到:

"Retailer Staff ".gsub(/.*$(\d+(\.\d+)?).*/, )
# => 5

发生什么事了?为什么同样的代码 运行 两次会给出两个答案? gsub 缓存什么东西吗?

您的代码没有真正意义,它没有按照您的想法进行。

</code> 是一个全局变量,因此第一个 <code>gsub 会将匹配的模式替换为 </code> <em>before</em> 你调用 <code>gsub。这个:

"Retailer Staff .60".gsub(/.*$(\d+(\.\d+)?).*/, )

相当于:

confusion = 
"Retailer Staff .60".gsub(/.*$(\d+(\.\d+)?).*/, confusion)

当你真的想说:

"Retailer Staff .60".gsub(/.*$(\d+(\.\d+)?).*/) {  }

这样 gsub 可以在屈服于障碍之前设置 </code>。</p> <p>一旦您了解了 <code> 的设置时间和评估时间,那么其他一切都将水到渠成。您的第一个 gsub 最终将 </code> 设置为 <code>'5.60',然后您的下一个电话只是一种过于复杂的说法:

"Retailer Staff ".gsub(/.*$(\d+(\.\d+)?).*/, '5.60')

并将 </code> 设置为 <code>'5'。等等。

我相信这是因为 </code> 实际上是对在最后一个处理的正则表达式中找到的第一个捕获组的全局引用:<a href="http://ruby-doc.org/core-2.4.2/Regexp.html#class-Regexp-label-Special+global+variables" rel="nofollow noreferrer">ruby 2.4 docs</a>。因此,在您的情况下,您可能已经测试了正则表达式并匹配了“5.60”。这是我 运行 在 ruby 2.0 中的注释片段:</p> <pre><code># Since no regex has executed yet is nil irb(main):001:0> "Retailer Staff .60".gsub(/.*$(\d+(\.\d+)?).*/, ) TypeError: no implicit conversion of nil into String from (irb):1:in 'gsub' from (irb):1 from /usr/bin/irb:12:in '<main>' irb(main):002:0> "Retailer Staff .60".gsub(/.*$(\d+(\.\d+)?).*/, 'some value') => "some value" irb(main):003:0> # Now we have executed a regex so is set => "5.60" irb(main):004:0> "Retailer Staff .60".gsub(/.*$(\d+(\.\d+)?).*/, ) => "5.60" irb(main):005:0> # This is still the same value because we matched the same string => "5.60" irb(main):006:0> "Retailer Staff ".gsub(/.*$(\d+(\.\d+)?).*/, ) => "5.60" irb(main):007:0> # Now we have matched the 5 so has the new value => "5" irb(main):008:0> "Retailer Staff ".gsub(/.*$(\d+(\.\d+)?).*/, ) => "5" irb(main):009:0> => "5"