为什么这段代码只修改数组中的最后一个文件?我的用户可以读取和写入这些文件。
%w(views/layout.rhtml views/admin/layout.rhtml).each do |file|
text = File.read(file)
File.open(file, 'w+') do |f|
f << text.gsub(/\?v=(\d+)/, "?v=#{$1.to_i + 1}")
end
end
最佳答案
您的问题是您没有使用 gsub
的 block 形式所以$1
并且类似的全局变量并不像您想象的那样设置。来自精美手册:
If replacement is a String it will be substituted for the matched text. It may contain back-references to the pattern‘s capture groups of the form
\\d
, where d is a group number, or\\k<n>
, where n is a group name. If it is a double-quoted string, both back-references must be preceded by an additional backslash. However, within replacement the special match variables, such as &$, will not refer to the current match.
还有:
In the block form, the current match string is passed in as a parameter, and variables such as
$1
,$2
,$&
, and$’
will be set appropriately. The value returned by the block will be substituted for the match on each call.
大胆的我的。另外,我省略了全局反引号:
$`
为了避免 Markdown 出现问题(如果有人知道如何在内联代码块中获得反引号,我将不胜感激)。
如果您这样做:
%w(views/layout.rhtml views/admin/layout.rhtml).each do |file|
text = File.read(file)
File.open(file, 'w+') do |f|
f << text.gsub(/\?v=(\d+)/) { "?v=#{$1.to_i + 1}" }
end
end
我想您会得到您正在寻找的结果。
关于ruby - 搜索/替换怪异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6577165/