用Ruby替换文件中的单词

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)

  • @Drew虽然不一样,但总是添加一个换行符,所以你在文档中会有一个空的最后一行.也不会短得多.但是你可以使用`f << filtered_data`. (2认同)

eng*_*nky 10

或者你可以把它做成一个班轮

File.write("hello.txt",File.open("hello.txt",&:read).gsub("install","latest"))
Run Code Online (Sandbox Code Playgroud)