Home
Preface
Chapter Selection
Programming Examples
Homework Problems
Homework Solutions MEA's
Search Useful Links

Programming Examples

Chapter 7 Programming Examples

FileReader:Class which reads the contents of a file
1  class FileReader
2   def initialize (fileName)
3     @file = File.open(fileName,"r")
4   end
5  
6   def readFile
7    	while (inputLine = @file.gets) 
8 	    wholeFile += inputLine
9	end
10  end
11  
12  def display
13	puts "Contents of Input File: \n" + readFile
14  end  
15 end


 
 
Reading and Displaying a File named test.dat
1  require 'file_reader.rb'
2
3  fr = FileReader.new("test.dat")
4  fr.readFile
5  fr.display



 
 
FileWriter:Sequentially writing to a file
1  class FileWriter 
2       def initialize (fileName)
4	    @file = File.new(fileName,"w")
5	end
6  
7       def writeLine (outputLine)
9	    @file.puts(outputLine)
10	end
11    
12	def close
13	    @file.close
14	end  
15 end



 
 
Reading one and and Outputting to Another with Line Numbers
1  require 'file_reader.rb'
2  require 'file_writer.rb'
3
4  fr = FileReader.new("test.dat")
5  fw = FileWriter.new("test.out")
6	
7  while (inputLine = fr.readLine) 
8      fw.writeline(''#{fr.lineno +1} \t #{inputLine}'')
9  end
10 fw.close
11 puts "Finished reading test.dat. Now look at test.out.”



 
 
Examples Using the Each Method
1  file = File.open('input.txt')
2  file.each do |line|
3     puts line.lineno + line
4  end


1  “Bread Hamburger Pasta Banana”.each do |food|
2     puts food
3  end