如何在Ruby中捕获按键? [英] How to capture a key press in Ruby?

查看:80
本文介绍了如何在Ruby中捕获按键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby中,我需要一个简单的线程,该线程将在每次按下键时运行一些代码.有办法吗?

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?

我需要能够捕获 Page Up Page Down

这是我尝试过的:

#!/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

这几乎可行.只有1个问题,每个击键后都需要按回车键.我猜这是因为缓冲了IO.

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.

推荐答案

您可以使用curses库捕获按键,而无需进行缓冲.

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

关键代码在这里:

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

您可以在github上找到更长的示例:

You can find a longer example on github:

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

这篇关于如何在Ruby中捕获按键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆