Skip to content

Instantly share code, notes, and snippets.

@julioterra
Created October 7, 2011 07:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save julioterra/1269663 to your computer and use it in GitHub Desktop.
Save julioterra/1269663 to your computer and use it in GitHub Desktop.
IO: sketch that tests different methods for reading keyboard input one line at a time.
# filename: io_line.rb
# sketch that tests different methods for reading keyboard input one line at a time.
# find out what approach to use to read the file
puts
puts "Reading data from the keyboard using line-based approach."
puts "Select a method to read in the keyboard input:"
puts " 1) each method"
puts " 2) gets method"
puts " 3) readline method"
puts " ** to quit from playing around type any number"
puts " ** the read and readlines method are designed to until the end of a file"
puts " these methods are not appropriate for keyboard input"
input = STDIN.gets.to_i
puts
# if input was 1 then use each method
if input == 1
puts "** EACH method "
STDIN.each do |n|
if n =~ /[a-z]+/; puts n
else; break; end
end
# if input was 2 then use gets method
elsif input == 2
puts "** GETS method:"
line = ""
puts line while ((line = STDIN.gets) =~ /[a-z]+/)
# if input was 3 then use readline method
elsif input == 3
puts "** READLINE method:"
line = ""
puts line while ((line = STDIN.readline) =~ /[a-z]+/)
# if input did not match then display error message
else
puts "** ERROR: your input didn't make sense"
end
puts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment