在 ruby 中写入文件-ag捕鱼王app官网

在 ruby 中写入文件

作者:迹忆客 最近更新:2023/03/20 浏览次数:

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

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.

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

发布时间:2024/02/05 浏览次数:181 分类:编程语言

本文演示了 ruby 中注入方法的不同用途。

发布时间:2023/03/21 浏览次数:240 分类:编程语言

本文介绍了在 ruby 程序中调用 shell 命令的各种方法。

发布时间:2023/03/21 浏览次数:86 分类:编程语言

简要讨论 ruby 中的模式匹配运算符及其使用方式。

发布时间:2023/03/21 浏览次数:89 分类:编程语言

本教程说明了如何在 ruby 中使用安全导航。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便
网站地图