Capturing key presses with the curses gem

--snip You can use the curses library to capture key presses 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

The key codes are here:

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

You can find a longer example on github:

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

Tags:
Source:
1926hrs.txt
Published:
13-12-2011 19:26