Hendrik Kleine Hendrik Kleine - 1 year ago 103
Ruby Question

Ruby: gets.chomp 1 keypress

I want to prompt a user to either press ESC or any other key. Pressing ESC will stop all further actions. Pressing ENTER (or any other key), will perform additional actions.

Pressing ENTER works fine, but gets waits for the user to actually press enter. Making it no very friendly.

Is there a way to continue after 1 keypress by the user?

puts "Press Enter to continue or ESC to quit..."
decision = gets.chomp

if decision != "^["
then puts "do this stuff"
puts "bye"

Answer Source

I believe you hardly understand what you are doing. First of all, it depends on OS you are using. I am aware of no one “standard” mechanism to be applicable to all operating systems.

Secondary, comparison against string, containing two characters, '^' and '[' is by no means the same as the check against ESC.

The last, but not the least: gets is buffering an input unless is pressed. What you need to read one char is IO#getc.

Here is working code for unix console:

puts "Press Enter to continue or ESC to quit..."
  system("stty raw -echo")
  decision = STDIN.getc
  system("stty -raw echo")

if decision.ord != 27
  puts "do this stuff"
  puts "bye"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download