Hendrik Kleine Hendrik Kleine - 4 months ago 15
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"
else
puts "bye"
end

Answer

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..."
begin
  system("stty raw -echo")
  decision = STDIN.getc
ensure
  system("stty -raw echo")
end

if decision.ord != 27
  puts "do this stuff"
else
  puts "bye"
end
Comments