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.
+7
A:
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
(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.
Jay
2008-10-06 16:14:35
That works so far, but unfortunately i get a numeric and not a string. du you know how to convert the numeric to the right ascii-character?
Nino
2008-10-06 16:33:07
Yes, just use str.chr to get the character corresponding to the numeric value. I've updated the post to reflect that
Jay
2008-10-06 16:50:46
thanks, much better now
Nino
2008-10-06 16:56:08
A:
rogerdpack
2010-07-06 06:44:04
+1
A:
This should be cross platform:
First you have to install highline:
gem install highline
Then it's as easy as:
require "highline/system_extensions"
include HighLine::SystemExtensions
print "Press any key:"
k = get_character
puts k.chr
mit
2010-10-21 01:51:51