1

I am writing a tiny interactive command line tool prompting the user to press a numeric key. It should continue directly after the first key press/input.

Currently I am doing this to capture the user's input

puts "yes, please ..."
gets.chomp

... however this requires pressing "enter" to confirm the input. How can return the input value right after the first key press?

Bernd
  • 11,133
  • 11
  • 65
  • 98
  • 1
    Looks like it has been asked before [http://stackoverflow.com/questions/8072623/get-single-char-from-console-immediately][1] [1]: http://stackoverflow.com/questions/8072623/get-single-char-from-console-immediately – Bala Oct 15 '13 at 13:31

1 Answers1

1

Try something like this:

puts 'Do you want to proceed? y/n'

loop do
  system("stty raw -echo")
  c = STDIN.getc
  system("stty -raw echo")

  case c
  when 'y'
    puts 'Yes'
    break
  when 'n'
    puts 'No'
    break
  else
    puts 'Please type "y" or "n"'
  end
end
Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168