3

In Ruby, I need a simple thread that would run some code every time a key in pressed. Is there a way to do that?

I need to be able to capture the Page Up and Page 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

This almost works. There is only 1 issue, one needs to hit return after every key stroke. I guess this is because of buffered IO.

Aleksandr Levchuk
  • 3,751
  • 4
  • 35
  • 47

1 Answers1

12

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

You can find a longer example on github:

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

spike
  • 9,794
  • 9
  • 54
  • 85