How to manipulate files in Ruby Introduction to _ruby topics

Source: Internet
Author: User
Tags foreach chmod mkdir readable first row

Ruby provides a complete set of implementation methods in the I/O-related kernel modules. All I/O methods come from the IO class.

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

This chapter will cover all the basic I/O features that are available for use in Ruby. For more features, refer to Ruby's IO class.
puts statement:

In the previous section, you specify the value of the variable and then use the declaration puts output.

Puts the statement to show that the program is stored in the variable value. This adds a new line, which is written out (output) at the end of each line.
Example:

#!/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 invoke STDIN from the user taking input from the standard screen.
For example:

The following code shows how to use the gets statement. This code prompts the user to enter a value that will be stored in a variable Val and will eventually print in 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, it prints the entire string on the screen, and the PUTC statement can be used to output one character at a time.
Instance:

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

#!/usr/bin/ruby

str= "Hello ruby!"
PUTC Str

This will produce the following results:

H

Print statement:

The print statement is a similar puts statement. The only difference is that the PRINT statement positions the cursor on the same line after the puts statement goes to the next line of printed content.
Instance:

#!/usr/bin/ruby

print "Hello World"
print "Good Morning"

This will produce the following results:

Hello Worldgood Morning

To open and close a file:

So far, we have been able to read and write standard inputs and outputs. We'll look at how to apply the actual data file.
File.new Method:

You can create a file object using the File.new method of reading, writing, or both, which needs to be based on the pattern string. Finally, you can use the File.close method to close the file.
Grammar:

Afile = file.new ("filename", "mode")
  # ... process the File
afile.close

File.Open Method:

You can use the method of the File.Open method to create a new file object and assign it to a file object. However, the difference between the File.Open method and the File.new method. The File.Open method differs in that it can be associated with a block and not in the File.new method.

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


Here is a different mode to open the file list:

Read and Write files:

In the same way, we have been using "simple" I/O all file objects. Therefore, gets reads one row from the standard input and the File.gets file reads one row from the file object.

However, I/O objects provide additional access methods that make life easier for us.
Sysread Method:

You can use this method to Sysread read the contents of a file. When you can open the file, the method used in any mode is sysread. For example:

The following is an 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
  content
else
  puts "unable to open file!"
End

This statement will output the first 20 characters of the file. Now place the file pointer in the 21st character.
Syswrite Method:

You can use the contents of method Syswrite to write to a file. You need to open the file in write mode using method Syswrite.
For example:

#!/usr/bin/ruby

afile = file.new ("Input.txt", "r+")
if Afile
  afile.syswrite ("ABCDEF")
Else
  puts "Unable to open file!"
End

This statement writes "ABCDEF" to the file.
Each_byte Method:

This method belongs to class File. Always associate a block method Each_byte. Consider the following code example::

#!/usr/bin/ruby

afile = file.new ("Input.txt", "r+")
if Afile
  afile.syswrite ("ABCDEF")
  Afile.each_ byte {|ch| putc ch; putc?}
Else
  puts "unable to open file!"
End

Pass the variable ch one by one character, and then display the following on the screen:

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 subclass of the IO class. Class IO There are also some methods that can be used to manipulate files.

One of the methods of the IO class is io.readlines. The content file row returned by this method. The following code shows how to use Io.readlines:

#!/usr/bin/ruby

arr = io.readlines ("Input.txt")
puts Arr[0]
puts Arr[1]

In this piece of code, the variable arr is an array. Input.txt each row of the file to arr the elements in the array. So arr[0] will be included in the first row, and arrival [1] will contain the second row of the file.
Io.foreach Method:

This method also returns the output of one line. The difference between the foreach and ReadLines methods is that the Foreach method can be associated with a block, and foreach does not return an array. For example:

#!/usr/bin/ruby

Io.foreach ("Input.txt") {|block| puts block}

This code passes the contents of the file, tests the rows of the variable block, and then the output is displayed on the screen.
To rename and delete a file:

You can rename and delete files using Ruby to programmatically use the rename and delete methods.

In the following example, rename an existing file Test1.txt:

#!/usr/bin/ruby

# Rename a file from Test1.txt to Test2.txt
file.rename ("Test1.txt", "Test2.txt")

The following example deletes an existing file test2.txt:

#!/usr/bin/ruby

# Delete file test2.txt
file.delete ("Text2.txt")

File mode and ownership:

Use the chmod mask method to change the schema or permissions/Access file list:

The following example changes the existing file Test.txt pattern Mask value:

#!/usr/bin/ruby

file = file.new ("Test.txt", "W")
File.chmod (0755)

The following table can help you choose a different mask for the chmod method:

File query:

The following command tests whether a file exists and then opens it:

#!/usr/bin/ruby

File.Open ("file.rb") if file::exists? ( "FILE.RB")

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

#!/usr/bin/ruby

# This returns either True or False
File.file? ( "Text.txt") 

Given whether the file name is a directory, the following command finds:

#!/usr/bin/ruby

# A directory
File::d irectory? ( "/usr/local/bin") # => True

# a file
::d irectory? ( "File.rb") # => False

The following command finds whether the file is readable, writable, or executable:

#!/usr/bin/ruby

file.readable? ( "Test.txt")  # => True
file.writable? ( "Test.txt")  # => True
file.executable? ( "Test.txt") # => False

The following command finds whether the file has a size of zero or no:

#!/usr/bin/ruby

File.zero? ( "Test.txt")   # => True

The file size returned by the following command:

#!/usr/bin/ruby

file.size? ( "Text.txt")   # => 1002

You can use the following command to find a type of file:

#!/usr/bin/ruby

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

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

The following commands can be used to discover when a file is created, modified, or last accessed:

#!/usr/bin/ruby

file::ctime ("Test.txt") # => Fri May/10:06:37-0700 2008 File::mtime
("Text.txt") # =&G T Fri 10:44:44-0700 2008
file::atime ("Text.txt") # => Fri May 09 10:45:01-0700 2008

Directories in Ruby:

All files are contained in a different directory, and Ruby does not address these issues. In view of the class processing files in the file, use the directory to process the Dir class.
navigating through the directory:

To change the contents of a Ruby program, you can use Dir.chdir below. This example changes the current directory/usr/bin.

Dir.chdir ("/usr/bin")

You can use Dir.pwd to find out what the current directory is:

Puts Dir.pwd # This'll return something Like/usr/bin

Get a list of files and directories using a specific directory, using dir.entries:

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

Dir.entries returns all items within the specified directory of an array. The Dir.foreach provides the same functionality:

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


A more straightforward way to get directory listings using the Dir class array method:

dir["/usr/bin/*"]

Create a directory:

You can use Dir.mkdir to create a table of contents:

Dir.mkdir ("Mynewdir")

You can also set a new directory permission (not an already existing one) with mkdir:

Note: Mask 755 Sets the permission owner, and the group says [everyone] is similar to rwxr-xr-x, R = Read, W = write, and x = Execute.

Dir.mkdir ("Mynewdir", 755)

To delete a directory:

You can delete a directory with Dir.delete. Dir.unlink and Dir.rmdir perform exactly the same functions and provide convenience.

Dir.delete ("TestDir")

To create a file and a temporary directory:

Temporary files are information that may be short-lived, but not permanently stored, during the execution of a program.

Dir.tmpdir provides a path to the temporary directory of the current system, although the method is not available by default. In order to make dir.tmpdir necessary to use the need for ' 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, and deletes it. Ruby's standard library also includes a library tempfile that can create temporary files:

Require ' tempfile '
  f = tempfile.new (' Tingtong ')
  f.puts "Hello"
  puts F.path
  f.close

Built-in features:

Here is the support feature of Ruby, which handles the complete list of files and directories:

    • The File Class and Methods.
    • Dir Class and Methods.

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.