0

I'm trying to read a character instantly from command line without use of Enter. The ruby (ruby 1.9.3p374) code that I'm using is the following:

require 'io/console'

ch = STDIN.getch
puts ch

until now everithing is working fine but now i want to put this code inside an infinite loop doing some other stuff, something like

loop do
  puts "..doing stuff.."
  ch = STDIN.getch
  if ch == 'q'
    break
  end
end

but this code always force that we press a key between each printing. I want a behaviour similar to STDIN.read_nonblock method but without having to press enter key after pressing one char.

Basically I want to print "..doing stuff.." until I press a certain key on keyboard but i don't want to use enter.

Any help will be appreciated. Thanks

1 Answers1

0

You could always use the built-in curses library to handle your interaction. It's very powerful and is used to construct keyboard-driven tools such as text editors.

The alternative is to use select to poll if STDIN is readable. Your terminal might be in a line-buffered state, so you'd need to adjust that before single keystrokes are received. This is something that Curses can handle for you.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • Thank you tadman. I will try to explore the curses library to check if I can find a solution to my problem. – Paulo Magalhães Apr 18 '13 at 09:36
  • It's worth noting that the enter problem might be due to the terminal being line buffered. By default, nothing is "sent" until a newline is received. This can be changed, though, but doing it with low-level calls is annoying. You'll also have to restore the terminal to the default state or you'll wreck other programs that depend on line buffering. Curses, while a bit dizzying to learn at first, can do a lot of this for you and is capable of doing a lot of things related to terminal management well. – tadman Apr 18 '13 at 14:37