Created
October 7, 2011 07:10
-
-
Save julioterra/1269664 to your computer and use it in GitHub Desktop.
IO: sketch that tests different methods for reading files one line or more at a time.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# filename: files_line.rb | |
# sketch that tests different methods for reading files one line or more at a time. | |
# open file to read | |
puts | |
puts "Creating a reference to file input stream" | |
f = File.new("../chapter_11/regex_scan.rb") | |
# find out what approach to use to read the file | |
puts "Select a line-based approach to read the file:" | |
puts " 1) read method" | |
puts " 2) each method" | |
puts " 3) gets method" | |
puts " 4) readline method" | |
puts " 5) readlines method" | |
input = STDIN.gets.to_i | |
puts | |
# if input was 1 then use read method | |
if input == 1 | |
puts "** READ method: " | |
puts f.read | |
# if input was 2 then use each method | |
elsif input == 2 | |
puts "** EACH method: " | |
f.each { |n| puts n } | |
# if input was 3 then use gets method | |
elsif input == 3 | |
puts "** GETS method: " | |
line = "" | |
# loop through file f until f.gets = nil | |
puts line while (line = f.gets) | |
# if input was 4 then use readline method | |
elsif input == 4 | |
puts "** READLINE method: " | |
line = "" | |
# loop through file f until f.readline returns an error | |
puts line while (line = f.readline) | |
# if input was 5 then use readlines each method | |
elsif input == 5 | |
puts "** READLINES method: " | |
lines = f.readlines | |
puts "#{lines}" | |
# if input did not match then display error message | |
else | |
puts "** ERROR: your input didn't make sense" | |
end | |
puts | |
# close the file | |
f.close |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment