From: Gabriele Marrone Date: 2006-11-12T05:35:12+09:00 Subject: Re: print message if user does nothing for x seconds? On 11/nov/06, at 21:07, ara.t.howard@noaa.gov wrote: > 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 Nice! May I suggest adding an optional validation block? I hope you don't mind if I slightly modify your code: def prompt question, opts = {}, &validation 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 invalid = (opts['invalid'] || opts[:invalid] || 'try again').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 } if validation && !validation.call(answer) answer = default puts invalid else break end rescue Timeout::Error print prod STDOUT.flush sleep 2 end } answer end answer = prompt('the question', 'timeout' => 5, 'max' => 2) { |s| s == "valid input\n" } -- Gabriele Marrone