Você está na página 1de 24

Chapter 8: Working with Files

By:
Kushal Jangid

Introduction

You can manipulate file directories (folders) and files from


within Ruby programs using methods from the Dir and File
classes. Ruby uses a number of global constants. Two global
constants that are important in working with files are ARGV (or
$* ) and ARGF (or $< ).

Directories
Dir.pwd,
Dir.chdir (or Dir.getwd ), and
Dir.mkdir

Dir.chdir( "/Users/mikejfz" )
home = Dir.pwd # => "/Users/mikejfz/"
p home # => "/Users/mikejfz"

Directories
Compare a variable storing a directory path with the current
directory:

ruby_progs = "/Users/mikejfz/Desktop/Ruby"
if not Dir.pwd == ruby_progs
Dir.chdir ruby_progs
end

Creating Directories
If you need a directory, create it with mkdir ; later on,
delete it with rmdir (or delete , a synonym of rmdir ):
To create :
Dir.mkdir( "/Users/mikejfz/sandbox" )
To Delete :
Dir.rmdir( "/Users/mikejfz/sandbox" )

Looking Inside Directories


Dir s class method entries returns an array that contains
all the entries found in a directory, including files, hidden
files, and other directories, one array element per entry.

Looking Inside Directories


Dir.entries( "/usr/local/src/ruby-1.8.6" ).each { |e| puts e }
The beginning of the output from this command looks like this:
.rbconfig.time
array.c
array.o
bcc32
bignum.c
bignum.o

The Directory Stream


dir = Dir.open( "/usr/local/src/ruby-1.8.6" )
dir.path # => "/usr/local/src/ruby-1.8.6"
dir.tell # => "."
dir.read # => 1
dir.tell # => ".."
dir.rewind # => rewind to beginning
dir.each { |e| puts e } # puts each entry in dir
dir.close # => close stream
The class method open (or new ) opens a directory stream on the given
directory. path tells you the path of the stream. tell returns the current
entry. read reads the next available entry from dir . rewind takes you
back to the beginning of the stream. each iterates through each entry in
dir .

Creating a New File


To create a new file and open it at the same time, use the File method
new , like this:
file = File.new( "file.rb", "w" ) # => #<File:file.rb>
The first argument names the new file, and the second argument
specifies the file
mode r for readable, w for writable, or x for executable.

File Modes

Opening an Existing File


file = File.open( "sonnet_129.txt" )
file.each { |line| print "#{file.lineno}. ", line }
file.close

The expression substitution syntax, that is, #{file.lineno} ,


inserts the line number in the output, followed by the line
from the file.

ARGV and ARGF


ARGV << "sonnet_129.txt"
print while gets

Remember that ARGV (or $* ) is an array, and each of its elements


is a filename submitted on the command line usually. But in this
case, we have appended a filename to ARGV directly with << , an
array method.

ARGV and ARGF


while line = ARGF.gets
print line
end

ARGF ( $< ) is, once again, a virtual concatenation of all the files
that appear on the command line. While there is a line to be
retrieved from files on the command line, argf.rb prints that line to
standard output.

Opening a URI
require 'open-uri'
url = "http://www.google.com/search?q=ruby"
open(url) { |page| page_content = page.read( )
Links = page_content.scan(/<aclass=l.*href=\"(.*?)\"/).flatten
links.each {|link| puts link}
}
The URI is read and scanned using a regular expression, looking for the
value of the href attribute on a (anchor) elements. Those matched
elements are stored in the links variable, and each is used to iterate over
the lot of them.

Deleting and Renaming Files


You can rename and delete files programmatically with Ruby using
the rename and delete methods. Type these lines into irb:
File.new( "books.txt", "w" )
File.rename( "books.txt", "chaps.txt" )
File.delete( "chaps.txt" )

File Inquiries
You can make all kinds of inquires about files with File methods. These
kinds of tests are often done before another file procedure is done. For
example, the following command tests whether a file exists before
opening it:
File::open("file.rb") if File::exists?( "file.rb" )
File.file?( "sonnet29.txt" ) # => true
Or find out if it is a directory with directory? : # try it with a directory
File::directory?( "/usr/local/bin" ) # => true

Array As a String
greeting = [ "Hello! ", "Bonjour! ", "Guten Tag!" ]
puts greeting.to_s # => Hello! Bonjour! Guten Tag!

Using shift and unshift


Another way to remove an element from an array is with the shift
method. This method returns the first element of an array ( nil if the
array is empty), and then removes the element, shifting all other elements
down by one.

dates = [ 4, 5, 6, 7 ] # => [4, 5, 6, 7]


dates.shift # => 4
p dates # => [5, 6, 7]
dates.unshift(2,3) # => [2, 3, 4, 5, 6, 7]

Deleting Elements
months = ["nil", "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug",
"sep", "oct", "nov", "dec"]
month_a.delete_at( 12 ) # => "dec"
p month_a # ["nil", "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug",
"sep", "oct", "nov"]

Arrays and Blocks


Array has an each method, toojust like lots of other Ruby
classes. each lets you iterate over every element in an array and
do something to it.

month_a.each { |e| print e.capitalize + " " }


Output : Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
The map method (and its synonym collect ) is similar to each ,
but it returns a new array instead of a string.
month_a_2007 = month_a.map { |e| e.capitalize + " 2007" }

Sorting Things and About Face


x = [ 2, 5, 1, 7, 23, 99, 14, 27 ]
Sorting x:
x.sort! # => [1, 2, 5, 7, 14, 23, 27, 99]

Multidimensional Arrays
A multidimensional array is an array of arrays. You create such
an array by giving array elements that are themselves arrays.
This is a two-dimensional array:
d2 = [ ["January", 2007],
["February", 2007],
["March", 2007] ]
Lets turn d2 into a one-dimensional array with flatten .
d2.flatten
# => ["January", 2007, "February", 2007, "March", 2007]

Multidimensional Arrays
A two-dimensional array is like a table, with rows and columns. Lets
try the transpose method on d2 , turning this:

d2 = [ ["January", 2007], ["February", 2007], ["March", 2007] ]


into this:
d2.transpose
# => => [["January", "February", "March"], [2007, 2007, 2007]]

Thank You

Você também pode gostar