How to capture keystroke in Ruby?

In Ruby, I need a simple thread that will run some code every time I press a key. Is there any way to do this?

I need to be able to record Page UpandPage Down

Here is what I tried:

#!/usr/bin/env ruby

Thread.new do
  while c = STDIN.getc
    puts c.chr
  end
end

loop do
  puts Time.new
  sleep 0.7
end

It almost works. There is only 1 problem, you need to strike back after each keystroke. I think this is due to I / O buffering.

+3
source share
1 answer

You can use the curses library to capture keystrokes without buffering.

require 'curses'

Curses.noecho # do not show typed keys
Curses.init_screen
Curses.stdscr.keypad(true) # enable arrow keys (required for pageup/down)

loop do
  case Curses.getch
  when Curses::Key::PPAGE
    Curses.setpos(0,0)
    Curses.addstr("Page Up")
  when Curses::Key::NPAGE
    Curses.setpos(0,0)
    Curses.addstr("Page Dn")
  end
end

Key codes are here:

http://ruby-doc.org/stdlib/libdoc/curses/rdoc/index.html

You can find a longer example on github:

https://github.com/grosser/tic_tac_toe/blob/master/bin/tic_tac_toe

+12

All Articles