Skip to content

Instantly share code, notes, and snippets.

@acook
Created December 2, 2012 18:42
Show Gist options
  • Select an option

  • Save acook/4190379 to your computer and use it in GitHub Desktop.

Select an option

Save acook/4190379 to your computer and use it in GitHub Desktop.
Read keypresses from user in terminal, including arrow keys using pure Ruby. This has since been folded into a much more robust gem called Remedy. https://rubygems.org/gems/remedy & https://github.com/acook/remedy
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)
@chirantan

Copy link
Copy Markdown

Great snippet! I'm facing a problem however… This is my output

right
left
app3
right
left
up
down
middle
middle
middle
middle
middle
middle
middle
middle
middle
middle
middle
middle
middle
middle
middle
middle
middle
middle
middle
middle
middle
middle
middle
middle

As you can see above, the middle (enter key) remains pressed for indefinitely amount of time. I'm not sure what's causing this. It's not just the enter key, happens with any. Wondering why. Any idea?

@Daxx

Daxx commented Nov 26, 2014

Copy link
Copy Markdown

Very helpful, thank you.

@macmv

macmv commented Oct 2, 2015

Copy link
Copy Markdown

Awesome! I just downloaded it, and it works great!

@tkovs

tkovs commented Apr 3, 2016

Copy link
Copy Markdown

Doesn't work on Windows

@blakeyoder

Copy link
Copy Markdown

Yes, can confirm it doesn't work on Windows, either

@sonjz

sonjz commented May 19, 2021

Copy link
Copy Markdown

super useful, 🙏

@acook

acook commented May 21, 2021

Copy link
Copy Markdown
Author

I'm glad this has helped people!

If you discover something that is also broken in Remedy please report it!

@mthunzi99

Copy link
Copy Markdown

Anyone found the windows solution yet?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment