我是 Ruby 的新手,我一直在尝试替换文件中的单词。其代码如下:
File.open("hello.txt").each do |li|
if (li["install"])
li ["install"] = "latest"
puts "the goal state set to install, changed to latest"
end
end
虽然 puts 中的消息被打印一次,但该文件的该行中的单词不会更改为“最新”。谁能告诉我这里出了什么问题?谢谢
最佳答案
您还需要写回文件。 File.open
不带任何参数打开文件以供读取。你可以试试这个:
# load the file as a string
data = File.read("hello.txt")
# globally substitute "install" for "latest"
filtered_data = data.gsub("install", "latest")
# open the file for writing
File.open("hello.txt", "w") do |f|
f.write(filtered_data)
end
关于ruby-on-rails - 用 Ruby 替换文件中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22335589/