Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby-如何使用脚本的输出编写新文件_Ruby - Fatal编程技术网

Ruby-如何使用脚本的输出编写新文件

Ruby-如何使用脚本的输出编写新文件,ruby,Ruby,我有一个简单的脚本,可以进行一些搜索和替换。 基本上是这样的: 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 如您所见,我想用输出编写一个新文件。如何执行此操作?输出到新文件的操作如下(不要忘记第二个参数): output=File.open(“outputfile

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

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

如您所见,我想用输出编写一个新文件。如何执行此操作?

输出到新文件的操作如下(不要忘记第二个参数):

output=File.open(“outputfile.yml”、“w”)

输出首先,您必须创建一个新文件,如newfile.txt

然后将脚本更改为

File.open("us_cities.yml", "r+") do |file|
  new_file = File.new("newfile.txt", "r+")
  while line = file.gets
  new_file.puts "do find a replace"
  end
end
这将生成一个包含输出的新文件

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
File.open("us_cities.yml", "r+") do |file|
  new_file = File.new("newfile.txt", "r+")
  while line = file.gets
  new_file.puts "do find a replace"
  end
end