Tutorial on processing file input and output in Ruby, and tutorial on ruby processing output

Source: Internet
Author: User

Tutorial on processing file input and output in Ruby, and tutorial on ruby processing output

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

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

This section describes all the basic I/O functions available in Ruby. For more functions, see the Ruby IO class.
Puts statement

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

The puts statement indicates that the program displays the value stored in the variable. This adds a new row at the end of each row.
Instance

#!/usr/bin/ruby val1 = "This is variable one"val2 = "This is variable two"puts val1puts val2

This produces the following results:

This is variable oneThis is variable two

Gets statement

The gets statement can be used to obtain user input from the standard screen named STDIN.
Instance

The following code demonstrates how to use the gets statement. This code will prompt you to enter a value, which will be stored in the variable val and finally printed on STDOUT.

#!/usr/bin/ruby puts "Enter a value :"val = getsputs val

This produces the following results:

Enter a value :This is entered valueThis is entered value

Putc statement

Unlike the puts statement, the puts statement outputs the entire string to the screen, and the putc statement can be used to output one character in sequence.
Instance

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

#!/usr/bin/ruby str="Hello Ruby!"putc str

This produces the following results:

H

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 content. When the print statement is used, the cursor is positioned in the same line.
Instance

#!/usr/bin/ruby print "Hello World"print "Good Morning"

This produces the following results:

Hello WorldGood Morning

Open and Close files

Up to now, you have read and written standard input and output. Now we will look at how to operate the actual data files.
File. new Method

You can use the File. new Method to create a File object for reading, writing, or reading/writing. The read/write permission depends on the mode string. Finally, you can use File. close to close the File.
Syntax

AFile = File. new ("filename", "mode") #... process File aFile. close

File. open Method

You can use the File. open method to create a new file object and assign the file object to the File. However, the File. open and File. new methods are slightly different. The difference is that the File. open method can be associated with the block, but the File. new method cannot.

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

The following table lists different file opening modes:

File Query

The following command checks whether the file exists before opening the file:

#!/usr/bin/ruby File.open("file.rb") if File::exists?( "file.rb" )

Run the following command to check whether the file is indeed a file:

#! /Usr/bin/ruby # returns <I> true </I> or <I> false </I> File. file? ("Text.txt ")

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

#! /Usr/bin/ruby # A directory File: directory? ("/Usr/local/bin") # => true # File: directory? ("File. rb") # => false

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

#!/usr/bin/ruby File.readable?( "test.txt" )  # => trueFile.writable?( "test.txt" )  # => trueFile.executable?( "test.txt" ) # => false

The following command checks whether the file size is zero:

#!/usr/bin/ruby File.zero?( "test.txt" )   # => true

The following command returns the file size:

#!/usr/bin/ruby File.size?( "text.txt" )   # => 1002

The following command is used to check the file type:

#!/usr/bin/ruby File::ftype( "test.txt" )   # => file

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

The following command is used to check the time when the file is created, modified, or accessed:

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

Ruby directory

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

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

Dir.chdir("/usr/bin")

You can view the current directory through Dir. pwd:
Puts Dir. pwd # the current directory is returned, similar to/usr/bin.

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

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

Dir. entries returns an array containing all the items in the specified directory. Dir. foreach provides the same functions:

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

A more concise way to get the directory list is to use the Dir class array method:

Dir["/usr/bin/*"]

Create directory

Dir. mkdir can be used to create directories:

Dir.mkdir("mynewdir")

You can also set permissions on the new directory (not an existing Directory) through mkdir:

Note: mask 755 sets the owner, group, and everyone (world [anyone]) permission to rwxr-xr-x, where r = read, w = write, x = execute.

Dir.mkdir( "mynewdir", 755 )

Delete directory

Dir. delete can be used to delete directories. Dir. unlink and Dir. rmdir perform the same functions, which provides us with convenience.

Dir.delete("testdir")

Create File & temporary directory

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

Dir. tmpdir provides the path to the temporary directory on the current system, but this method is not available by default. To make Dir. tmpdir available, use the required 'tmpdir' is necessary.

You can use Dir. tmpdir and File. join together to create a temporary File independent of the Platform:

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. The Ruby standard library also contains a library named Tempfile, which can be used to create temporary files:

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.