如何编码"按键继续"

Cyr*_*ris 8 ruby

我正在尝试实现一个简单的"按任意键继续".我将此消息打印到控制台,我想在按下一个键后将其擦除.

在" 使用ruby在命令提示符中写入以前的输出行 "之后,我尝试了这段代码:

def continue
  print "Press any key to continue\r"
  gets
end

puts "An awesome story begins..."
continue
puts "And ends after 2 lines"
Run Code Online (Sandbox Code Playgroud)

但是,这个\r技巧不起作用,下一个puts不会删除句子.是因为不同的功能背景吗?将gets产生一个新行?或者因为我在Windows操作系统上?

Yul*_*ule 18

您可以使用IO类中的STDIN,而不是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"    
Run Code Online (Sandbox Code Playgroud)

这有额外的好处,它只需要输入一个字符(getch- 获得字符),允许"按任意键"无需返回或输入即可工作.