Outline
In this blog post, I will show you how to use File I/O in Ruby.
Stream
When exchanging data with files in Ruby, the Stream
concept is used. In Ruby, we use the stream to read and write the data.
The next is the procedure for reading and writing the file in Ruby.
- Prepare a stream for flowing data.
- Flow data from the file to the program or the program to the file.
- Close the stream.
Files are largely divided text files and binary files. And also, streams have the string stream and bytes stream.
Stream | Description |
---|---|
string stream | it controls 16 bits Unicode string data. |
bytes stream | it controls 8 bits data. |
We use the IO
class to control the stream and we use the File
class that is the sub-class of IO
class to input/output the files.
Class | Description |
---|---|
IO Class | Provide the feature to exchange data between outside and inside of the program. |
File Class | Provide writing and reading of the file. |
이번 블로그에서는 텍스트만 다루도록 하겠습니다.
Read File
The following is the procedure to read the file.
Open the file
To open the file, we use
open
method orFile.open
method.io = open(fileName, "r") io = File.open(fileName, "r")
We can set the mode when we open the file.
Mode Description r Read mode w Write mode a Read/Write mode Read the data
You can use
read
method to read all data like below.io.read
If the file is too big and read it at once, you can get the memory issue. If the file is too bing, you can use
gets
method to get the line by line.while data = io.gets puts data end
Close the file
If you finish all actions with the file, you can use
close
method to close the file.io.close
Write the file
Below is the procedure to write the text to the file.
Open the file
텍스트 파일에 데이터를 쓰기 위해서는,
w
나a
모드를 사용하여 파일을 열어야 합니다.io = open(fileName, "w")
Write the file
You can use
write
method to write the data to the file like below.io.write("Hello world")
Close the file
If you write all data to the file, you can close the file like below.
io.close
Example
The next is the file input/output example.
data = "Hello world"
io = open("example.txt", "w")
io.write(data)
io.close
io = open("example.txt")
io.each {|line|
puts line
}
io.close
Completed
We’ve seen how to input/output the file in Ruby. It’s very important to use close
to close the file after you finish to use the file. If you don’t close the file, other processes can’t use read the file and the errors occur.
Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!
App promotion
Deku
.Deku
created the applications with Flutter.If you have interested, please try to download them for free.