Skip to content

Instantly share code, notes, and snippets.

@julioterra
Created October 7, 2011 07:07
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/1269657 to your computer and use it in GitHub Desktop.
Save julioterra/1269657 to your computer and use it in GitHub Desktop.
IO: sketch that tests different methods for reading keyboard input one byte at a time.
# filename: io_byte.rb
# sketch that tests different methods for reading keyboard input one byte at a time.
# find out what approach to use to read the file
puts
puts "Reading data from the keyboard using byte-based approach."
puts "Select the method to read the keyboard input:"
puts " 1) using getc method"
puts " 2) using getbyte method"
puts " 3) using readchar method"
puts " 4) using readbyte method"
puts " ** to quit from playing around type any number"
input = STDIN.gets.to_i
puts
# if input was 1 then use getc method
if input == 1
puts "** GETC method:"
char = ""
print char while ((char = STDIN.getc) =~ /[a-z\W]+/)
# if input was 2 then use getbyte method
elsif input == 2
puts "** GETBYTE method:"
char = 0
print char, " " while ((char = STDIN.getbyte.to_i) > 57 || char < 49)
# if input was 3 then use readchar method
elsif input == 3
puts "** READCHAR method:"
char = ""
print char while ((char = STDIN.readchar) =~ /[a-z\W]+/)
# if input was 4 then use readbyte method
elsif input == 4
puts "** READBYTE method:"
char = 0
print char, " " while ((char = STDIN.readbyte) > 57 || char < 49)
# 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