Ruby - How to write a new file with output from script

后端 未结 2 1188
借酒劲吻你
借酒劲吻你 2021-02-04 00:39

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 f         


        
2条回答
  •  梦谈多话
    2021-02-04 01:08

    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.

提交回复
热议问题