我需要找到每个“$”,并使用计数将其更改为数字。例如str = "foo $ bar $ foo $ bar $ * run code here * => "foo 1 bar 2 foo 3 bar 4
感觉这应该比我正在制作它要容易得多。这是我的代码:
def counter(file)
f = File.open(file, "r+")
count = 0
contents = f.readlines do |s|
if s.scan =~ /\$/
count += 1
f.seek(1)
s.sub(/\$/, count.to_s)
else
puts "Total changes: #{count}"
end
end
end
但是我不确定我是否打算使用.match
,.scan
,.find
或其他任何内容。
当我运行它时,它没有出现任何错误,但它也没有改变任何东西。
答案 0 :(得分:1)
scan的语法不正确,应该抛出错误。
您可以尝试这一行:
count = 0
str = "foo $ bar $ foo $ bar $ "
occurences = str.scan('$')
# => ["$", "$", "$", "$"]
occurences.size.times do str.sub!('$', (count+=1).to_s) end
str
# => "foo 1 bar 2 foo 3 bar 4 "
<强>说明:强>
我在字符串中发现$
的所有出现,然后我在迭代中使用sub!,因为它一次只替换第一次出现。
注意:您可能希望通过使用带有边界匹配的正则表达而不是普通scan
来改进"$"
行,因为它将替换$
甚至来自单词。例如:exa$mple
也会替换为:exa1mple
为什么您的代码没有抛出错误?
如果您阅读了有关readlines的说明,您会发现:
将名称指定的整个文件读取为单独的行,并且 返回数组中的那些行。
当它一次读取整个文件时,沿此方法没有值传递块。以下示例将使其更加清晰:
contents = f.readlines do |s|
puts "HELLO"
end
# => ["a\n", "b\n", "c\n", "d\n", "asdasd\n", "\n"] #lines of file f
正如您所见,“HELLO”永远不会被打印出来,显示块代码永远不会被执行。