如何在不按Enter的情况下获取单个字符? [英] How to get a single character without pressing enter?

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

问题描述

如何在不使用Enter的情况下使用Ruby从终端获得单个键盘字符? 我尝试了Curses::getch,但这对我来说真的不起作用.

How can I get a single keyboard character from the terminal with Ruby without pressing enter? I tried Curses::getch, but that didn't really work for me.

推荐答案

http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/2999

#!/usr/bin/ruby

begin
  system("stty raw -echo")
  str = STDIN.getc
ensure
  system("stty -raw echo")
end
p str.chr

(在我的OS X系统上测试过,可能无法移植到所有Ruby平台上).有关其他建议,请参见 http://www.rubyquiz.com/quiz5.html ,其中包括Windows.

(Tested on my OS X system, may not be portable to all Ruby platforms). See http://www.rubyquiz.com/quiz5.html for some additional suggestions, including for Windows.

这篇关于如何在不按Enter的情况下获取单个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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