tutorial on processing the input and output of files in Ruby _ruby topics

Source: Internet
Author: User
Tags foreach mkdir readable

Ruby provides a complete set of I/O-related methods that are implemented in the kernel (Kernel) module. All I/O methods derive from the IO class.

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

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

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

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

#!/usr/bin/ruby
 
val1 = "This are variable one"
Val2 = "This is variable two"
puts Val1
puts

This will produce the following results:

This is variable the one is
variable two

Gets statement

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

The following code shows how to use the gets statement. The code prompts the user for a value that will be stored in the variable Val and will eventually be printed on the STDOUT.

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

This will produce the following results:

Enter A value: This is
entered value entered value

PUTC statement

Unlike the puts statement, the puts statement prints the entire string to the screen, and the PUTC statement can be used to output one character at a turn.
Instance

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

#!/usr/bin/ruby
 
str= "Hello ruby!"
PUTC Str

This will produce 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, while using the print statement, the cursor is positioned on the same line.
Instance

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

This will produce the following results:

Hello Worldgood Morning

Opening and closing files

As of now, you have read and write standard input and output. Now, we'll look at 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")
  # ... Working with files
Afile.close

File.Open method

You can use the File.Open method to create a new file object, and assign the file object to files. However, there is a difference between the File.Open and the file.new methods. The difference is that the File.Open method can be associated with a block, and the File.new method cannot.

File.Open ("filename", "mode") do |afile|
  # ... process the file end

The following table lists the different modes of opening files:

File query

The following command checks to see if a file already exists before opening the file:

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

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

#!/usr/bin/ruby
 
# back to <i>true</i> <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::d irectory? ( "/usr/local/bin") # => True
 
# a file
::d irectory? ( "File.rb") # => False

The following command checks to see if the file is readable, writable, and executable:

#!/usr/bin/ruby
 
file.readable? ( "Test.txt")  # => True
file.writable? ( "Test.txt")  # => True
file.executable? ( "Test.txt") # => False

The following command checks to see if the file size is zero:

#!/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 is used to check the type of file:

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

The Ftype method identifies the type of file by returning one of the following values: file, directory, Characterspecial, blockspecial, FIFO, link, socket, or unknown.

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

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

Table of contents in Ruby

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

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 by dir.pwd:
Puts Dir.pwd # Returns the current directory, similar to/usr/bin

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

Puts Dir.entries ("/usr/bin"). Join (')

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

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

A more concise way to get a directory listing is by using the method of a class array of Dir:

dir["/usr/bin/*"]

Create a table of contents

Dir.mkdir can be used to create a directory:

Dir.mkdir ("Mynewdir")

You can also set permissions on the new directory (not already existing directories) by mkdir:

Note: The Mask 755 setting owner (owner), group, and everyone (world [anyone]) has permissions of rwxr-xr-x, where r = Read reads, W = Write write, x = Execute.

Dir.mkdir ("Mynewdir", 755)

Delete Directory

Dir.delete can be used to delete a directory. Dir.unlink and Dir.rmdir perform the same functions, providing us with convenience.

Dir.delete ("TestDir")

Create a File & Temp directory

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

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

You can use Dir.tmpdir and file.join to create a platform-independent temporary 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 the 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

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.