没有错误但没有结果

no Errors but no Result

我需要找到每次出现的“$”并使用计数将其更改为数字。例如 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 或其他任何东西。

当我 运行 执行此操作时,它不会出现任何错误,但也不会改变任何内容。

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 的描述,您会发现:

Reads the entire file specified by name as individual lines, and returns those lines in an array.

由于它一次读取整个文件,因此此方法没有值传递块。下面的例子会更清楚:

 contents = f.readlines do |s|
     puts "HELLO"
 end
 # => ["a\n", "b\n", "c\n", "d\n", "asdasd\n", "\n"] #lines of file f

如您所见,"HELLO" 从未被打印出来,表明块代码从未被执行。