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 ruby
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 writing
4. open a file Creating the file object opens the file: >> f = File.new("abc.rb") => #<File:abc.rb>
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)>
6. read a file return a single line >> f.gets => "aaa" return the whole file after current position >> f.read => "aaabbbccc" returns file as an array of lines >> f.readlines => ["aaa", "bbb", "ccc"]
8. iterate over lines File objects are enumerable: >> f.each {|line| puts line} aaa bbb ccc
9. use any enumerable method >> f.map {|line| line.chomp + "... "} => ["ddd... ", "eee... ", "fff4th letter to 6th... "] >> f.any? {|line| line =~ /ddd/ } => false >> f.rewind => 0 >> f.any? {|line| line =~ /ddd/ } => true
10. write to a file “r+” argument >> g = File.new("def.rb", "r+") => #<File:def.rb> >> g.read => "dddeeefff" >> g.puts "4th letter to 6th” >> g.rewind >> g.read => "dddeeefff4th letter to 6th"