Skip to content

Instantly share code, notes, and snippets.

@mlpinit
Forked from acook/keypress.rb
Last active August 29, 2015 14:08
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 mlpinit/90e53e34746e2df21cd6 to your computer and use it in GitHub Desktop.
Save mlpinit/90e53e34746e2df21cd6 to your computer and use it in GitHub Desktop.
require 'io/console'
# Reads keypresses from the user including 2 and 3 escape character sequences.
def read_char
STDIN.echo = false
STDIN.raw!
input = STDIN.getc.chr
if input == "\e" then
input << STDIN.read_nonblock(3) rescue nil
input << STDIN.read_nonblock(2) rescue nil
end
ensure
STDIN.echo = true
STDIN.cooked!
return input
end
# oringal case statement from:
# http://www.alecjacobson.com/weblog/?p=75
def show_single_key
c = read_char
case c
when " "
puts "SPACE"
when "\t"
puts "TAB"
when "\r"
puts "RETURN"
when "\n"
puts "LINE FEED"
when "\e"
puts "ESCAPE"
when "\e[A"
puts "UP ARROW"
when "\e[B"
puts "DOWN ARROW"
when "\e[C"
puts "RIGHT ARROW"
when "\e[D"
puts "LEFT ARROW"
when "\177"
puts "BACKSPACE"
when "\004"
puts "DELETE"
when "\e[3~"
puts "ALTERNATE DELETE"
when "\u0003"
puts "CONTROL-C"
exit 0
when /^.$/
puts "SINGLE CHAR HIT: #{c.inspect}"
else
puts "SOMETHING ELSE: #{c.inspect}"
end
end
show_single_key while(true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment