Escolar Documentos
Profissional Documentos
Cultura Documentos
By:
Kushal Jangid
Introduction
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" )
File Modes
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.
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!
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"]
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:
Thank You