I am trying to implement a simple "Press any key to continue". I print this message to the console, and I want to erase it after a key is pressed.
Following "Writing over previously output lines in the command prompt with ruby", I tried this piece of code:
def continue
print "Press any key to continue\r"
gets
end
puts "An awesome story begins..."
continue
puts "And ends after 2 lines"
However, the \r
trick doesn't work and the next puts
won't erase the sentence. Is it because of a different function context? The gets
spawns a newline? Or because I'm on Windows OS?
Use getch() : printf("Let the Battle Begin!\ n"); printf("Press Any Key to Continue\n"); getch();
If you add raw_input('Press any key to exit') it will not display any error codes but it will tell you that the program exited with code 0. For example this is my first program.
You can use STDIN from the IO class, rather than gets
.
require 'io/console'
def continue_story
print "press any key"
STDIN.getch
print " \r" # extra space to overwrite in case next sentence is short
end
puts "An awesome story begins..."
continue_story
puts "And ends after 2 lines"
This has the added bonus that it only requires one character to be entered (getch
- get character) allowing the 'press any key' to work without a return or enter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With