user918069
user918069

Reputation: 109

Is there a way to get a single keystroke in ruby?

I need a way to check the keyboard, see if any single key has been pressed and if so get the key and if not, leave and go about my business. I only need to check about a half dozen keys. And I will return to check often (i.e., this check is in a part of the program that repeats endlessly [as long as the program is running.] Alternatively, I guess I could also implement it as an interrupt, i.e., do the rest of the loop and go get the key when pressed.

Because get and getc both wait for a return, they won't work for me. I found examples in java and on windows but I'm on a Mac.

Upvotes: 3

Views: 741

Answers (1)

DigitalRoss
DigitalRoss

Reputation: 146073

To read a character immediately without giving the tty device a chance to edit the characters and wait for a return, you would need something like this:

system 'stty cbreak'
$stdout.syswrite 'How now: '
q = $stdin.sysread 1
puts
puts "You typed #{q} it seems."
system 'stty cooked'

To add a check for a character being available, extend it to do a non-blocking read...

def read1maybe
  return $stdin.read_nonblock 1
rescue Errno::EAGAIN
  return ''
end

system 'stty cbreak'
while true
  q = read1maybe
  break if q.length > 0
  puts 'you did not change anything'
  sleep 1
end
puts
puts "You typed #{q} it seems."
system 'stty cooked'

For something more elaborate, see the standard library curses package. You may also find io/console useful.

Upvotes: 4

Related Questions