Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

The input and output of the Ruby file


May 12, 2021 Ruby


Table of contents


The input and output of the Ruby file

Ruby provides a complete set of I/O-related methods, implemented in the Kernel module. All I/O methods are derived from the IO class.

Class IO provides all the basic methods, such as read, write, gets, puts, readline, getc, and printf.

This section explains the underlying I/O functions available in all Rubys. For more functions, check out Ruby's IO class.

Puts statement

In the previous section, you assign a variable and then print the output using the puts statement.

The puts statement instructs the program to display the values stored in the variable. This adds a new line at the end of each line.

#!/usr/bin/ruby

val1 = "This is variable one"
val2 = "This is variable two"
puts val1
puts val2

This results in the following:

This is variable one
This is variable two

Gets statement

Gets statements can be used to get user input from a standard screen called STDIN.

The following code demonstrates how to use gets statements. The code prompts the user to enter a value that will be stored in the variable val and will eventually be printed on STDOUT.

#!/usr/bin/ruby

puts "Enter a value :"
val = gets
puts val

This results in the following:

Enter a value :
This is entered value
This is entered value

Putc statement

Unlike puts statements, put statements output the entire string to the screen, while putc statements can be used to output one character in turn.

The output of the following code is just the character H:

#!/usr/bin/ruby

str="Hello Ruby!"
putc str

This results in the following:

H

The print statement

The print statement is similar to the puts statement. The only difference is that the puts statement jumps to the next line after the output, and when the print statement is used, the cursor is positioned on the same line.

#!/usr/bin/ruby

print "Hello World"
print "Good Morning"

This results in the following:

Hello WorldGood Morning

Open and close files

Up to now, you have read and written standard inputs and outputs. Now we'll see how to manipulate the actual data file.

File.new method

You can use the File.new method to create a File object for reading, writing, or reading and writing, depending on the mode string. Finally, you can use the File.close method to close the file.

Grammar

aFile = File.new("filename", "mode")
   # ... 处理文件
aFile.close

File.open method

You can use the File.open method to create a new file object and assign it to a file. H owever, there is a difference between the File.open and File.new methods. The difference is that the File.open method can be associated with blocks, while the File.new method cannot.

File.open("filename", "mode") do |aFile|
   # ... process the file
end

The following table lists the different modes of opening a file:

模式 描述
r 只读模式。文件指针被放置在文件的开头。这是默认模式。
r+ 读写模式。文件指针被放置在文件的开头。
w 只写模式。如果文件存在,则重写文件。如果文件不存在,则创建一个新文件用于写入。
w+ 读写模式。如果文件存在,则重写已存在的文件。如果文件不存在,则创建一个新文件用于读写。
a 只写模式。如果文件存在,则文件指针被放置在文件的末尾。也就是说,文件是追加模式。如果文件不存在,则创建一个新文件用于写入。
a+ 读写模式。如果文件存在,则文件指针被放置在文件的末尾。也就是说,文件是追加模式。如果文件不存在,则创建一个新文件用于读写。

Read and write files

Methods for simple I/O are also available for all file objects. So gets reads a row from the standard input, and aFile.gets reads a row from the file object aFile.

However, I/O objects provide additional settings for access methods, which facilitates us.

The sysread method

You can use the method sysread to read the contents of the file. W hen using the method sysread, you can open the file in any mode. For example:

Here's the input text file:

This is a simple text file for testing purpose.

Now let's try to read this file:

#!/usr/bin/ruby

aFile = File.new("input.txt", "r")
if aFile
   content = aFile.sysread(20)
   puts content
else
   puts "Unable to open file!"
end

The statement enters the first 20 characters of the file. The file pointer is placed at the 21st character in the file.

syswrite method

You can use the method syswrite to write to a file. W hen using the method syswrite, you need to open the file in write mode. For example:

#!/usr/bin/ruby

aFile = File.new("input.txt", "r+")
if aFile
   aFile.syswrite("ABCDEF")
else
   puts "Unable to open file!"
end

The statement is written to the file "ABCDEF".

each_byte method

The method belongs to the class File. M ethod each_byte is an iterative string for each character. Take a look at the following example of code:

#!/usr/bin/ruby

aFile = File.new("input.txt", "r+")
if aFile
   aFile.syswrite("ABCDEF")
   aFile.rewind
   aFile.each_byte {|ch| putc ch; putc ?. }
else
   puts "Unable to open file!"
end

Characters are passed one after another to the variable ch and then displayed on the screen, as follows:

A.B.C.D.E.F.s. .a. .s.i.m.p.l.e. .t.e.x.t. .f.i.l.e. .f.o.r. .t.e.s.t.i.n.g. .p.u.r.p.o.s.e...

IO.readlines method

Class File is a sub-class of class IO. Class IO also has some methods for operating files.

IO.readlines is a method in the IO class. T he method returns the contents of the file line by line. The following code shows the use of method IO.readlines:

#!/usr/bin/ruby

arr = IO.readlines("input.txt")
puts arr[0]
puts arr[1]

In this code, the variable arr is an array. E ach .txt the file input will be an element in array arr. Therefore, arr will contain the first line, and arr1 will contain the second line of the file.

IO.foreach method

The method also returns the output line by line. T he difference between method foreach and method readlines is that method foreach is associated with a block. H owever, unlike the method readlines, the method foreach does not return an array. For example:

#!/usr/bin/ruby

IO.foreach("input.txt"){|block| puts block}

This code will pass the contents of the file test line by line to the variable block, and the output will be displayed on the screen.

Rename and delete files

You can rename and delete files using the rename and delete methods.

The following instance renames an existing file test1 .txt:

#!/usr/bin/ruby

# 重命名文件 test1.txt 为 test2.txt
File.rename( "test1.txt", "test2.txt" )

The following instance removes an existing file test2 .txt:

#!/usr/bin/ruby

# 删除文件 test2.txt
File.delete("text2.txt")

File mode and ownership

Use the chmod method with mask to change the file's pattern or permission/access list:

The following example changes the pattern of an .txt test to a mask value:

#!/usr/bin/ruby

file = File.new( "test.txt", "w" )
file.chmod( 0755 )

The following table lists the different masks that can be used in the chmod method:

掩码 描述
0700 rwx 掩码,针对所有者
0400 r ,针对所有者
0200 w ,针对所有者
0100 x ,针对所有者
0070 rwx 掩码,针对所属组
0040 r ,针对所属组
0020 w ,针对所属组
0010 x ,针对所属组
0007 rwx 掩码,针对其他人
0004 r ,针对其他人
0002 w ,针对其他人
0001 x ,针对其他人
4000 执行时设置用户 ID
2000 执行时设置所属组 ID
1000 保存交换文本,甚至在使用后也会保存

File query

The following command checks whether a file already exists before opening it:

#!/usr/bin/ruby

File.open("file.rb") if File::exists?( "file.rb" )

The following command queries whether a file is indeed a file:

#!/usr/bin/ruby

# 返回 true 或false
File.file?( "text.txt" ) 

The following command checks whether a given file name is a directory:

#!/usr/bin/ruby

# 一个目录
File::directory?( "/usr/local/bin" ) # => true

# 一个文件
File::directory?( "file.rb" ) # => false

The following command checks whether the file is readable, writeable, and executable:

#!/usr/bin/ruby

File.readable?( "test.txt" )   # => true
File.writable?( "test.txt" )   # => true
File.executable?( "test.txt" ) # => false

The following command checks whether the file is zero in size:

#!/usr/bin/ruby

File.zero?( "test.txt" )      # => true

The following command returns the size of the file:

#!/usr/bin/ruby

File.size?( "text.txt" )     # => 1002

The following command checks the type of file:

#!/usr/bin/ruby

File::ftype( "test.txt" )     # => file

The ftype method identifies the type of file by returning a value in the following: file, directory, characterSpecial, blockSpecial, fifo, link, socket, or unknown.

The following command checks when the file was created, modified, or last accessed:

#!/usr/bin/ruby

File::ctime( "test.txt" ) # => Fri May 09 10:06:37 -0700 2008
File::mtime( "text.txt" ) # => Fri May 09 10:44:44 -0700 2008
File::atime( "text.txt" ) # => Fri May 09 10:45:01 -0700 2008

The directory in Ruby

All files are included in the directory, and Ruby provides a way to work with the files and directories. The File class is used to work with files, and the Dir class is used to work with directories.

Browse the catalog

To change the directory in the Ruby program, use Dir.chdir. The following example changes the current directory to /usr/bin.

Dir.chdir("/usr/bin")

You can view the current directory through Dir.pwd:

puts Dir.pwd # 返回当前目录,类似 /usr/bin

You can use Dir.entries to get a list of files and directories in the specified directory:

puts Dir.entries("/usr/bin").join(' ')

Dir.entries return an array that contains all the items in the specified directory. Dir.foreach provides the same functionality:

Dir.foreach("/usr/bin") do |entry|
   puts entry
end

A more concise way to get a list of directories is by using Dir's array of classes:

Dir["/usr/bin/*"]

Create a directory

Dir.mkdir can be used to create directories:

Dir.mkdir("mynewdir")

You can also set permissions on a new directory (not an existing directory) via mkdir:

Note: The mask 755 sets the permissions of the owner (owner), the group to which it belongs, and everyone to rwxr-xr-x, where r s read read, w s write write, x s execute.

Dir.mkdir( "mynewdir", 755 )

Delete the directory

Dir.delete can be used to delete directories. Dir.unlink and Dir.rmdir do the same for our convenience.

Dir.delete("testdir")

Create a file and a temporary directory

Temporary files are information that is simply created during program execution but is not permanently stored.

Dir.tmpdir provides the path to the temporary directory on the current system, but this method is not available by default. In order for Dir.tmpdir to be available, it is necessary to use the necessary 'tmpdir'.

You can use Dir.tmpdir with File.join to create a temporary platform-independent file:

require 'tmpdir'
   tempfilename = File.join(Dir.tmpdir, "tingtong")
   tempfile = File.new(tempfilename, "w")
   tempfile.puts "This is a temporary file"
   tempfile.close
   File.delete(tempfilename)

This code creates a temporary file, writes data to it, and then deletes the file. Ruby's standard library also contains a library called Tempfile, which can be used to create temporary files:

require 'tempfile'
   f = Tempfile.new('tingtong')
   f.puts "Hello"
   puts f.path
   f.close

Built-in functions

Here's a complete list of built-in functions in Ruby that handle files and directories: