File I/O in Ruby

2020-12-16 hit count image

Let's see how to use File I/O in Ruby.

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.

  1. Prepare a stream for flowing data.
  2. Flow data from the file to the program or the program to the file.
  3. Close the stream.

Files are largely divided text files and binary files. And also, streams have the string stream and bytes stream.

StreamDescription
string streamit controls 16 bits Unicode string data.
bytes streamit 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.

ClassDescription
IO ClassProvide the feature to exchange data between outside and inside of the program.
File ClassProvide writing and reading of the file.

이번 블로그에서는 텍스트만 다루도록 하겠습니다.

Read File

The following is the procedure to read the file.

  1. Open the file

    To open the file, we use open method or File.open method.

     io = open(fileName, "r")
     io = File.open(fileName, "r")
    

    We can set the mode when we open the file.

    ModeDescription
    rRead mode
    wWrite mode
    aRead/Write mode
  2. 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
    
  3. 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.

  1. Open the file

    텍스트 파일에 데이터를 쓰기 위해서는, wa 모드를 사용하여 파일을 열어야 합니다.

     io = open(fileName, "w")
    
  2. Write the file

    You can use write method to write the data to the file like below.

     io.write("Hello world")
    
  3. 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

You can use the applications that are created by this blog writer Deku.
Deku created the applications with Flutter.

If you have interested, please try to download them for free.

Posts