Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to code "press key to continue"

Tags:

ruby

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?

like image 331
Cyril Duchon-Doris Avatar asked Jan 04 '16 15:01

Cyril Duchon-Doris


People also ask

How do you code Press any key to continue?

Use getch() : printf("Let the Battle Begin!\ n"); printf("Press Any Key to Continue\n"); getch();

How do you press a key to exit in Python?

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.


1 Answers

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.

like image 163
Yule Avatar answered Oct 23 '22 11:10

Yule