将一行添加到Ruby文件中 [英] Prepend a single line to file with Ruby

查看:117
本文介绍了将一行添加到Ruby文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想像这样在Ruby的文件顶部添加一行:

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" on its own line
hello
something
else

以下代码仅替换了整个文件的内容:

The following code just replaces the contents of the entire file:

f = File.new('myfile', 'w')
f.write "test string"

推荐答案

这是一个非常常见的任务:

This is a pretty common task:

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

设置测试:

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

这是实际的代码:

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)

证明它有效:

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

哪个输出:

hello
something
else
---
something
else

您不想尝试将文件完全加载到内存中.这将一直有效,直到您获得的文件大于RAM分配,并且计算机进入抓取甚至崩溃的状态为止.

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.

这篇关于将一行添加到Ruby文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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