如何在 Ruby 中捕获按键操作?
在 Ruby 中,我需要一个简单的线程,每次按下按键时都会运行一些代码。有办法做到这一点吗?
我需要能够捕获 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。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用curses库来捕获按键而无需缓冲。
关键代码在这里:
http://ruby-doc.org/stdlib /libdoc/curses/rdoc/index.html
您可以在 github 上找到更长的示例:
https://github.com/grosser/tic_tac_toe/blob/master/bin/tic_tac_toe
You can use the curses library to capture key presses without buffering.
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