From: ara.t.howard@... Date: 2006-11-12T05:07:28+09:00 Subject: Re: print message if user does nothing for x seconds? On Sun, 12 Nov 2006, Ben Thomas wrote: > Hi all, > > Only just started using ruby so this may be really simple to do, but here > goes: > > I'm trying to write a program that asks a user to enter their sex using > "gets" but if the user doesn't type anything for about 5 seconds I want to > print a message, like "Please enter something..." then go back to the gets > prompt. I've tried using the "sleep x" method but it doesn't seem to work > because once gets has been initiated it gets stuck there until something is > entered. > > Oh I don't have to use gets, but this is the only method of input I'm aware > of at the moment > > Hope this makes sense, > Ben if you're on windows give up now. otherwise try this: harp:~ > cat a.rb require 'timeout' def prompt question, opts = {} timeout = Integer(opts['timeout'] || opts[:timeout] || 42) max = Integer(opts['max'] || opts[:max] || 42) default = opts['default'] || opts[:default] prod = (opts['prod'] || opts[:prod] || 'hey! wake up!').to_s answer = default prompt = "\r#{ question }: " prod = "\r#{ prod }" if prompt.size > prod.size prod += (' ' * (prompt.size - prod.size)) end if prod.size > prompt.size prompt += (' ' * (prod.size - prompt.size)) end max.times{ begin print prompt STDOUT.flush Timeout::timeout(timeout){ answer = gets } break rescue Timeout::Error print prod STDOUT.flush sleep 2 end } answer end answer = prompt 'the question', 'timeout' => 5, 'max' => 2 p 'answer' => answer -a -- my religion is very simple. my religion is kindness. -- the dalai lama