Prepend a single line to file with Ruby

后端 未结 8 663
再見小時候
再見小時候 2020-12-14 19:35

I\'d like to add a single line to the top a of file with Ruby like this:

# initial file contents
something
else

# file contents after prepending \"hello\" o         


        
8条回答
  •  攒了一身酷
    2020-12-14 20:06

    This is a pretty common task:

    original_file = './original_file'
    new_file = original_file + '.new'
    

    Set up the test:

    File.open(original_file, 'w') do |fo|
      %w[something else].each { |w| fo.puts w }
    end
    

    This is the actual code:

    File.open(new_file, 'w') do |fo|
      fo.puts 'hello'
      File.foreach(original_file) do |li|
        fo.puts li
      end
    end
    

    Rename the old file to something safe:

    File.rename(original_file, original_file + '.old')
    File.rename(new_file, original_file)
    

    Show that it works:

    puts `cat #{original_file}`
    puts '---'
    puts `cat #{original_file}.old`
    

    Which outputs:

    hello
    something
    else
    ---
    something
    else
    

    You don't want to try to load the file completely into memory. That'll work until you get a file that is bigger than your RAM allocation, and the machine goes to a crawl, or worse, crashes.

    Instead, read it line by line. Reading individual lines is still extremely fast, and is scalable. You'll have to have enough room on your drive to store the original and the temporary file.

提交回复
热议问题