I want to pause a Ruby script if any key is pressed, then later resume if any key is pressed. How do I do that? For example, here is a code snippet that doesn't work:
pause = false
Thread.new do
loop do
if $stdin.ready? and $stdin.getc
puts "got #{s}"
pause ^= true # toggle pause variable
end
end # loop do
end # Thread.new
loop do
next if pause == true
# do stuff if not paused
end # loop do
First do require 'io/console'
Only works in Ruby >= 2.0
pause = false
while STDIN.getch != "\r"
if pause == true
puts "do something"
end
pause = !pause
end
This will resume the code for every key press alternatively.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.