如何在一段时间后从Ruby中的终端获取字符串?

时间:2015-02-09 14:18:16

标签: ruby gets

我试图创建一个命令行程序,询问用户输入,但只在一定时间后获取字符串(例如:5秒)。

我目前正在使用gets.chomp,但这需要返回。

任何人都知道任何有用的方法吗?

2 个答案:

答案 0 :(得分:4)

@danmanstx的答案帮助我构建了工作示例(我猜它可以在Linux / MacOS上运行):

require "timeout"
def gets_timeout( prompt, secs )
  puts
  s = ''
  print prompt + " [timeout=#{secs}secs]: "
  begin
    system("stty raw echo")
    Timeout::timeout( secs ) { loop { s += STDIN.getc } } 
  rescue Timeout::Error
    puts "*timeout"
  ensure
    system("stty -raw echo")
    puts
    puts "We got: [#{s}]"
  end 
end

gets_timeout('hello',3)

Matz的额外学分。希望它有所帮助。

答案 1 :(得分:2)

您可以使用标准库中的超时

require "timeout"
def gets_timeout( prompt, secs )
  puts
  print prompt + "timeout=#{secs}secs]: "
  Timeout::timeout( secs ) { gets }
rescue Timeout::Error
  puts "*timeout"
  nil  # return nil if timeout
end

并运行它

2.1.5 :010 > test = gets_timeout('hello',3)
hello[timeout=3secs]: *timeout
 => nil 
2.1.5 :011 > test
 => nil 
2.1.5 :012 > test = gets_timeout('hello',3)
hello[timeout=3secs]: test
 => "test\n" 
2.1.5 :013 > test
 => "test\n" 

我发现了这个例子 https://www.ruby-forum.com/topic/206770