How to capture a pressed key?


How can I capture a key from keyboard in a console program? I mean, I
want to get an answer consisted of only one letter and the user will
not press “enter”. Just a key, that’s all.

Thank you.

print "Enter your name: "
name = gets

to get the first letter of ‘name’ you would access it by name[0,1]

Oh, I know the “gets”. But user will need to press “enter” in order to
“gets” to get something. I want to let the interpreter get a letter
WITHOUT pressing the enter key.

Are you running on Windows or Linux?

In Windows, you can do something like this:

require ‘Win32API’

$win32_console_kbhit =“msvcrt”, “_kbhit”, [], ‘I’)
$win32_console_cputs =“msvcrt”, “_cputs”, [‘P’], ‘I’)
$win32_console_getch =“msvcrt”, “_getch”, [], ‘I’)

def console_input_ready?
$ != 0

def console_input

def console_output( str )
$ str )

while true
if console_input_ready? then
ch = console_input
print “ch: <#{ch.chr}>\n”
console_output( “.” )
sleep 0.5

Gulp! I thought that could be done in two or three lines… :frowning:

It’s just not as easy as it may seem. This is true of any language.
Basically it depends on the environment (UI) that you’re using to
interface with the user. I would suggest (perhaps) Ncurses, since it’s
designed to handle that sort of thing (the shell isn’t). Perhaps I’ll
write a simple Ncurses gem to do this for you sometime…

Good luck.


You might want to look into the curses/ncurses library for Ruby. This
does what
you want, but there might be a bit too much overhead for what your
planning to do.

Another thing that comes to mind is using non-blocking IO on stdin.
not even sure if this is possible tho.

require ‘curses’
def get_char_now();
char = Curses.getch
return char

warning - code is approximate, you have to lookup Curses docs.
Depending on your application, it might make sense just to use curses
for everything, then there is no need to start/stop it every time.

Curses work on windows in cygwin, I haven’t tried the native installer.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs