在 Ruby 中写入文件

Nurudeen Ibrahim 2022年5月18日 Ruby Ruby File
在 Ruby 中写入文件

Ruby 中的 File 类有一个用于写入文件的 write() 方法。该方法返回写入的长度并确保文件自动关闭。它具有以下语法。

File.write('/your/file/path', 'Message content')

让我们将一条简单的消息写入文件。

File.write('my-file.txt', 'A simlpe message.')

上面的代码帮助我们创建一个名为 my-file.txt 的文件(如果它尚不存在),并允许我们编写 A simlpe message. 到文件。如果文件已经存在,代码将覆盖文件及其内容。

Ruby 没有覆盖文件内容,而是提供了一种通过指定 mode 选项附加到内容的方法,示例如下所示。

File.write("my-file.txt", " Another simple message\n", mode: 'a')

上例中的 \n 是一个换行符,这意味着我们将写入此文件的以下消息应该转到下一行。让我们写另一条消息来确认这一点。

File.write("my-file.txt", "This message should go on the next line", mode: 'a')

作为总结上述解释的一种方式,让我们编写一个简单的程序,将五行文本写入文件。

todos = [
  "wake up, shower, and leave for work",
  "Pick up John from school",
  "Meet with team to practice presentation",
  "Dinner with friends",
  "Relax and bedtime."
]

todos.each_with_index do |todo, index|
  File.write("todo-list.txt", "#{index + 1}. #{todo}\n", mode: 'a')
end

下面是运行程序后的 todo-list.txt 文件内容。

输出:

1. wake up, shower, and leave for work
2. Pick up John from school
3. Meet with team to practice presentation
4. Dinner with friends
5. Relax and bedtime.
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe