att*_*182 5 ruby string ruby-on-rails file
我是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
Run Code Online (Sandbox Code Playgroud)
当put中的消息被打印一次时,该单词在该文件的那一行中不会变为"latest".谁能告诉我这里有什么问题?谢谢
Iva*_*rea 17
您还需要回写该文件.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
Run Code Online (Sandbox Code Playgroud)
eng*_*nky 10
或者你可以把它做成一个班轮
File.write("hello.txt",File.open("hello.txt",&:read).gsub("install","latest"))
Run Code Online (Sandbox Code Playgroud)