You can use Kernel::select to write a helper method as follows:
def gets_with_timeout(sec, timeout_val = nil) return gets.chomp if select([$stdin], nil, nil, sec) timeout_val end
Then you can use it like this:
puts "How are you?" ans = gets_with_timeout(5) puts ans || "User did not respond"
source share