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.
相关问题
- How to specify memcache server to Rack::Session::M
- Why am I getting a “C compiler cannot create execu
- reference to a method?
- ruby 1.9 wrong file encoding on windows
- gem cleanup shows error: Unable to uninstall bundl
相关文章
- Ruby using wrong version of openssl
- Difference between Thread#run and Thread#wakeup?
- how to call a active record named scope with a str
- “No explicit conversion of Symbol into String” for
- Segmentation fault with ruby 2.0.0p247 leading to
- How to detect if an element exists in Watir
- uninitialized constant Mysql2::Client::SECURE_CONN
- ruby - simplify string multiply concatenation
http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/2999
(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.
Note: This is and old answer and the solution no longer works on most systems.
But the answer could still be useful for some environments, where the other methods don't work. Please read the comments below.
First you have to install highline:
Then try if the highline method works for you:
And if you are building curses application, you need to call
http://www.ruby-doc.org/stdlib-1.9.3/libdoc/curses/rdoc/Curses.html#method-c-cbreak
Raw mode (
stty raw -echo
) unfortunately causes control-C to get sent in as a character, not as a SIGINT. So if you want blocking input like above, but allow the user to hit control-C to stop the program while it's waiting, make sure to do this:And if you want non-blocking input -- that is, periodically check if the user has pressed a key, but in the meantime, go do other stuff -- then you can do this:
Note that you don't need a special SIGINT handler for the non-blocking version since the tty is only in raw mode for a brief moment.
@Jay gave a great answer, but there are two problems:
A simple fix for that is to save previous tty state and use following parameters:
-icanon
- disable canonical input (ERASE and KILL processing);isig
- enable the checking of characters against the special control characters INTR, QUIT, and SUSP.In the end you would have a function like this:
Since ruby 2.0.0, there is a 'io/console' in the stdlib with this feature