Is it possible to get each char from STDIN once it is provided (without waiting for return key)?
Asked
Active
Viewed 1.4k times
3 Answers
68
This is possible with Ruby 1.9.3's new getch
method:
require 'io/console'
input = STDIN.getch
Docs (Core): http://ruby-doc.org/core-2.3.0/IO.html#class-IO-label-io-2Fconsole
Docs (Lib): http://ruby-doc.org/stdlib-2.3.0/libdoc/io/console/rdoc/IO.html#method-i-getch
Source: https://github.com/ruby/ruby/tree/trunk/ext/io/console

J-_-L
- 9,079
- 2
- 40
- 37
-
1
-
Thanks, shout out to you in this answer here: http://stackoverflow.com/a/20081966/8047 – Dan Rosenstark Nov 19 '13 at 21:06
-
Don't forget to add `exit if input=="\u0018" or input=="\u0003"` if you are in a loop – Paul Verschoor May 30 '20 at 09:51
4
Yes, there are numerous ways to do this, and besides gems you can directly manipulate with terminfo through gems for termios, ncurses or stty program.
tty_param = `stty -g`
system 'stty raw'
a = IO.read '/dev/stdin', 1
system "stty #{tty_param}"
print a

tensai_cirno
- 914
- 1
- 7
- 13
2
Use the Highline gem:
require "highline/system_extensions" # gem install highline
include HighLine::SystemExtensions
print "Enter one character: "
char = get_character
puts char.chr
from JEG II's blog.