Ruby - 如何使用脚本的输出编写新文件 [英] Ruby - How to write a new file with output from script

查看:35
本文介绍了Ruby - 如何使用脚本的输出编写新文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的脚本,可以进行一些搜索和替换.基本上就是这样:

I have a simple script that does some search and replace. This is basically it:

File.open("us_cities.yml", "r+") do |file|
  while line = file.gets
  "do find a replace"
  end
  "Here I want to write to a new file"
end

如您所见,我想用输出编写一个新文件.我该怎么做?

As you can see I want to write a new file with the output. How can I do this?

推荐答案

输出到新文件可以像这样(不要忘记第二个参数):

Outputting to a new file can be done like this (don't forget the second parameter):

output = File.open( "outputfile.yml","w" )
output << "This is going to the output file"
output.close

所以在你的例子中,你可以这样做:

So in your example, you could do this :

File.open("us_cities.yml", "r+") do |file|
  while line = file.gets
    "do find a replace"
  end
  output = File.open( "outputfile.yml", "w" )
  output << "Here I am writing to a new file"
  output.close      
end

如果要追加到文件中,请确保将输出文件的开头置于循环之外.

If you want to append to the file, make sure you put the opening of the output file outside of the loop.

这篇关于Ruby - 如何使用脚本的输出编写新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆