file operations

24
 Chapter 8: Working with Files By: Kushal Jangid

Upload: kingjangid

Post on 07-Mar-2016

219 views

Category:

Documents


0 download

DESCRIPTION

File Operations in Ruby

TRANSCRIPT

Page 1: File Operations

7/21/2019 File Operations

http://slidepdf.com/reader/full/file-operations-56dcb1172ac59 1/24

 

Chapter 8: Working with Files

By:Kushal Jangid

Page 2: File Operations

7/21/2019 File Operations

http://slidepdf.com/reader/full/file-operations-56dcb1172ac59 2/24

 

Introduction

You can manipulate file directories (folders) and files from

within Ruby programs using methods from the Dir and Fileclasses Ruby uses a number of global constants !wo globalconstants that are important in wor"ing with files are #R$% (or&' ) and #R$F (or & )

Page 3: File Operations

7/21/2019 File Operations

http://slidepdf.com/reader/full/file-operations-56dcb1172ac59 3/24

 

Directories

DirpwdDirchdir (or Dirgetwd ) and

Dirm"dir

Dirchdir( *+,sers+mi"e-f.* )

home / Dirpwd 0 /1 *+,sers+mi"e-f.+*p home 0 /1 *+,sers+mi"e-f.*

Page 4: File Operations

7/21/2019 File Operations

http://slidepdf.com/reader/full/file-operations-56dcb1172ac59 4/24

 

Directories

2ompare a 3ariable storing a directory path with the currentdirectory:

ruby4progs / *+,sers+mi"e-f.+Des"top+Ruby*if not Dirpwd // ruby4progs

Dirchdir ruby4progs

end

Page 5: File Operations

7/21/2019 File Operations

http://slidepdf.com/reader/full/file-operations-56dcb1172ac59 5/24

 

Creating Directories

5f you need a directory create it with m"dir 6 later ondelete it with rmdir (or delete a synonym of rmdir ):

!o create :Dirm"dir( *+,sers+mi"e-f.+sandbo7* )

!o Delete :Dirrmdir( *+,sers+mi"e-f.+sandbo7* )

Page 6: File Operations

7/21/2019 File Operations

http://slidepdf.com/reader/full/file-operations-56dcb1172ac59 6/24

 

Looking Inside Directories

Dir 8s class method entries returns an array that containsall the entries found in a directory including files hidden

files and other directories one array element per entry

Page 7: File Operations

7/21/2019 File Operations

http://slidepdf.com/reader/full/file-operations-56dcb1172ac59 7/24

 

Looking Inside Directories

Direntries( *+usr+local+src+ruby9;<* )each = >e> puts e ?

!he beginning of the output from this command loo"s li"e this:

rbconfigtimearrayc

arrayobcc@Abignumcbignumo

Page 8: File Operations

7/21/2019 File Operations

http://slidepdf.com/reader/full/file-operations-56dcb1172ac59 8/24

 

The Directory Stream

dir / Diropen( *+usr+local+src+ruby9;<* )dirpath 0 /1 *+usr+local+src+ruby9;<*dirtell 0 /1 **dirread 0 /1 dirtell 0 /1 **dirrewind 0 /1 rewind to beginningdireach = >e> puts e ? 0 puts each entry in dirdirclose 0 /1 close stream

!he class method open (or new ) opens a directory stream on the gi3endirectory path tells you the path of the stream tell returns the currententry read reads the ne7t a3ailable entry from dir rewind ta"es you

bac" to the beginning of the stream each iterates through each entry indir

Page 9: File Operations

7/21/2019 File Operations

http://slidepdf.com/reader/full/file-operations-56dcb1172ac59 9/24

 

Creating a New File

!o create a new file and open it at the same time use the File methodnew li"e this:

file / Filenew( *filerb* *w* ) 0 /1 0File:filerb1

!he first argument names the new file and the second argumentspecifies the filemode r for readable w for writable or 7 for e7ecutable

Page 10: File Operations

7/21/2019 File Operations

http://slidepdf.com/reader/full/file-operations-56dcb1172ac59 10/24

 

File odes

Page 11: File Operations

7/21/2019 File Operations

http://slidepdf.com/reader/full/file-operations-56dcb1172ac59 11/24

 

!pening an "#isting File

file / Fileopen( *sonnet4ACt7t* )fileeach = >line> print *0=filelineno? * line ?fileclose

!he e7pression substitution synta7 that is 0=filelineno? inserts the line number in the output followed by the linefrom the file

Page 12: File Operations

7/21/2019 File Operations

http://slidepdf.com/reader/full/file-operations-56dcb1172ac59 12/24

 

$%&' and $%&F

#R$% *sonnet4ACt7t*print while gets

Remember that #R$% (or &' ) is an array and each of its elementsis a filename submitted on the command line usually But in thiscase we ha3e appended a filename to #R$% directly with anarray method

Page 13: File Operations

7/21/2019 File Operations

http://slidepdf.com/reader/full/file-operations-56dcb1172ac59 13/24

 

$%&' and $%&F

while line / #R$Fgetsprint line

end

#R$F ( & ) is once again a 3irtual concatenation of all the files

that appear on the command line hile there is a line to beretrie3ed from files on the command line argfrb prints that line tostandard output

Page 14: File Operations

7/21/2019 File Operations

http://slidepdf.com/reader/full/file-operations-56dcb1172ac59 14/24

 

!pening a (%I

reEuire open9uriurl / *http:++wwwgooglecom+searchGE/ruby*open(url) = >page> page4content / pageread( )

Hin"s / page4contentscan(+aclass/l'href/I*('G)I*+)flattenlin"seach =>lin"> puts lin"??

!he ,R5 is read and scanned using a regular e7pression loo"ing for the

3alue of the href attribute on a (anchor) elements !hose matchedelements are stored in the lin"s 3ariable and each is used to iterate o3erthe lot of them

Page 15: File Operations

7/21/2019 File Operations

http://slidepdf.com/reader/full/file-operations-56dcb1172ac59 15/24

 

Deleting and %enaming Files

You can rename and delete files programmatically with Ruby usingthe rename and delete methods !ype these lines into irb:

Filenew( *boo"st7t* *w* )Filerename( *boo"st7t* *chapst7t* )Filedelete( *chapst7t* )

Page 16: File Operations

7/21/2019 File Operations

http://slidepdf.com/reader/full/file-operations-56dcb1172ac59 16/24

 

File In)uiries

You can ma"e all "inds of inEuires about files with File methods !hese"inds of tests are often done before another file procedure is done Fore7ample the following command tests whether a file e7ists before

opening it:

File::open(*filerb*) if File::e7istsG( *filerb* )

FilefileG( *sonnetACt7t* ) 0 /1 true

r find out if it is a directory with directoryG : 0 try it with a directory

File::directoryG( *+usr+local+bin* ) 0 /1 true

Page 17: File Operations

7/21/2019 File Operations

http://slidepdf.com/reader/full/file-operations-56dcb1172ac59 17/24

 

$rray $s a String

greeting / *LelloM * *Bon-ourM * *$uten !agM* Nputs greetingto4s 0 /1 LelloM Bon-ourM $uten !agM

Page 18: File Operations

7/21/2019 File Operations

http://slidepdf.com/reader/full/file-operations-56dcb1172ac59 18/24

 

(sing shi*t and unshi*t

#nother way to remo3e an element from an array is with the shiftmethod !his method returns the first element of an array ( nil if thearray is empty) and then remo3es the element shifting all other elementsdown by one

dates / O P < Q N 0 /1 O P < QNdatesshift 0 /1 Op dates 0 /1 P < QN

datesunshift(A@) 0 /1 A @ O P < QN

Page 19: File Operations

7/21/2019 File Operations

http://slidepdf.com/reader/full/file-operations-56dcb1172ac59 19/24

 

Deleting "lements

months / *nil* *-an* *feb* *mar* *apr* *may* *-un* *-ul* *aug**sep* *oct* *no3* *dec*N

month4adelete4at( A ) 0 /1 *dec*p month4a 0 *nil* *-an* *feb* *mar* *apr* *may* *-un* *-ul* *aug*

*sep* *oct* *no3*N

Page 20: File Operations

7/21/2019 File Operations

http://slidepdf.com/reader/full/file-operations-56dcb1172ac59 20/24

 

$rrays and +locks

#rray has an each method too-ust li"e lots of other Rubyclasses each lets you iterate o3er e3ery element in an array anddo something to it

month4aeach = >e> print ecapitali.e * * ?

utput : Jan Feb Sar #pr Say Jun Jul #ug Tep ct Uo3 Dec

!he map method (and its synonym collect ) is similar to each but it returns a new array instead of a string

month4a4AVVQ / month4amap = >e> ecapitali.e * AVVQ* ?

Page 21: File Operations

7/21/2019 File Operations

http://slidepdf.com/reader/full/file-operations-56dcb1172ac59 21/24

 

Sorting Things and $,out Face

7 / A P Q A@ CC O AQ N

Torting 7:

7sortM 0 /1 A P Q O A@ AQ CCN

Page 22: File Operations

7/21/2019 File Operations

http://slidepdf.com/reader/full/file-operations-56dcb1172ac59 22/24

 

ultidimensional $rrays

# multidimensional array is an array of arrays You create suchan array by gi3ing array elements that are themsel3es arrays!his is a two9dimensional array:

dA / *January* AVVQN*February* AVVQN*Sarch* AVVQN N

Het8s turn dA into a one9dimensional array with flatten

dAflatten0 /1 *January* AVVQ *February* AVVQ *Sarch* AVVQN

Page 23: File Operations

7/21/2019 File Operations

http://slidepdf.com/reader/full/file-operations-56dcb1172ac59 23/24

 

ultidimensional $rrays

# two9dimensional array is li"e a table with rows and columns Het8stry the transpose method on dA turning this:

dA / *January* AVVQN *February* AVVQN *Sarch* AVVQN Ninto this:

dAtranspose

0 /1 /1 *January* *February* *Sarch*N AVVQ AVVQ AVVQNN

Page 24: File Operations

7/21/2019 File Operations

http://slidepdf.com/reader/full/file-operations-56dcb1172ac59 24/24

 

Thank -ou