ruby文件
In this tutorial we will learn about File handling in Ruby programming language. We will learn how to read data from a file, write data into a file, append data in an existing file with simple code examples. So let's get started.
在本教程中,我们将学习Ruby编程语言中的文件处理。 我们将学习如何通过简单的代码示例从文件读取数据,将数据写入文件,将数据追加到现有文件中。 因此,让我们开始吧。
(Ruby: Reading a File)
Reading files
读取文件非常简单。
This is the content of the file named sample.txt
. Now, we are going to read the contents of this file.
这是名为sample.txt
的文件的内容。 现在,我们将读取该文件的内容。
This small piece of code reads the contents of any file. You might be confused that there is no statement about the file name. We can specify the file name in the Command Prompt
while running the program.
没有关于文件名的声明 。 我们可以在运行程序时在Command Prompt
指定文件名。
We run by: ruby files.rb sample.txt
Here's the output:
这是输出:
This is one method of reading the file. We could also read the file by specifying the name of the file in the program. Like this:
这是一种读取文件的方法。 我们也可以通过在程序中指定文件名来读取文件。 像这样:
Here, we are opening the file using open
method. Variable file acts as a file handler here. So, for each line we are calling the gets
method using the variable
file and storing it in the variable line and printed using puts
method.
在这里,我们使用open
方法打开文件。 可变文件在这里充当文件处理程序 。 因此,对于每一行,我们都使用variable
文件调用gets
方法,并将其存储在变量行中,并使用puts
方法进行打印。
The output of the program is :
该程序的输出为:
(Ruby: Writing in a Files)
We have to create a File object
using new
method for reading data from files or writing data to files.
我们必须使用new
方法创建File object
以便从文件读取数据或将数据写入文件。
Here fil is the file object which is created using the new
method. The new method has two parameters, the first parameter is the name
of the file and the second parameter is the mode
. w
represents write mode to a file. We are using the file object fil
with the print
and puts
method to literally write to the file.
fil是使用new
方法创建的文件对象。 新方法有两个参数,第一个参数是文件name
,第二个参数是mode
。 w
表示文件的写入模式 。 我们将文件对象fil
与print
和puts
方法一起使用,以字面上的方式写入文件。
When we are finished, we should always close
the file. It is a good practice to always close
the file when done. If we don't close the file, the file maybe corrupted when we try to open it later sometimes. The data printed using print
and puts
method are stored in the buffer, the buffer is flushed
完成后,我们应该始终close
文件。 最好在完成后始终close
文件。 如果我们不关闭文件,则有时我们稍后尝试打开它时,文件可能已损坏。 使用print
和puts
方法print
的数据存储在缓冲区中 ,当我们关闭文件时,将刷新 缓冲区
The output of the program is :
该程序的输出为:
Actually, nothing happens when we execute the program. But when we view the file, the content is written in the file. Here is another example,
文件时
翻译自: https://www.studytonight.com/ruby/file-handling-in-ruby
ruby文件