Files IO

661 views

Published on

Published in: Technology, Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
661
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
12
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Files IO

  1. 1. I/O AND FILESFriday, March 4, 2011
  2. 2. IO: INPUT/OUTPUT • IO class is the basis for all input and output in Ruby • IO objects represent readable and/or writable connections to disk files, keyboards & screens • File is a subclass of IO and allows for reading and writing files in rubyFriday, March 4, 2011
  3. 3. COMMON MODES FOR OPENING I/O PORTS • "r" Read-only, starts at beginning of file (default) • "r+" Read-write, starts at beginning of file • "w" Write-only, truncates existing file to zero length or creates a new file for writing • "w+" Read-write, truncates existing file to zero length or creates a new file for reading and writingFriday, March 4, 2011
  4. 4. OPEN A FILE • Creating the file object opens the file: >> f = File.new("abc.rb") => #<File:abc.rb>Friday, March 4, 2011
  5. 5. OPEN FILE – WITH A BLOCK • File.open is synonomous with File.new, except that it can take a block: >> File.open(“abc.rb", "r+") do |f| f << "hello" end => #<File:abc.rb (closed)>Friday, March 4, 2011
  6. 6. READ A FILE • return a single line >> f.gets => "aaan" • return the whole file after current position >> f.read => "aaanbbbnccc" • returns file as an array of lines >> f.readlinesFriday, March 4, 2011
  7. 7. POSITION & REWIND >> f.rewind => 0 >> f.pos => 0 >> f.gets => "aaan" >> f.pos => 4Friday, March 4, 2011
  8. 8. ITERATE OVER LINES • File objects are enumerable: >> f.each {|line| puts line} aaa bbb cccFriday, March 4, 2011
  9. 9. USE ANY ENUMERABLE METHOD >> f.map {|line| line.chomp + "... "} => [”aaa... ", ”bbb... ", ”ccc... "] >> f.any? {|line| line =~ /aaan/ } => false >> f.rewind => 0 >> f.any? {|line| line =~ /aaan/ } => trueFriday, March 4, 2011
  10. 10. WRITE TO A FILE • “w+” argument >> my_file = File.new("data.txt", "w+") => #<File:def.rb> >> my_file.write("something") => 9 >> my_file.rewind => 0 >> my_file.readFriday, March 4, 2011
  11. 11. DIRECTORIES >> d = Dir.new("/Users/liahhansen/s/dir") => #<Dir:/Users/liahhansen/s/dir> >> d.entries => [".", "..", "abc.rb", "anothersubdir", "def.rb", "ghi.rb", "subdirectory"]Friday, March 4, 2011
  12. 12. COUNT FILES IN DIRECTORY >> i=0 => 0 >> d.each {|x| i+=1; puts i} 1 2 3 4 5 6 7Friday, March 4, 2011
  13. 13. ITERATE OVER FILES IN DIRECTORY >> ruby_files = Dir["*.rb"] => ["abc.rb", "def.rb", "ghi.rb"] >> ruby_files.map do |file| "rb_" + file end => ["rb_abc.rb", "rb_def.rb",Friday, March 4, 2011

×