tags:

views:

1341

answers:

3

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
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
Yes, just use str.chr to get the character corresponding to the numeric value. I've updated the post to reflect that
Jay
thanks, much better now
Nino
+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