From: "Brian Schröder" Date: 2004-12-10T01:43:05+09:00 Subject: Re: Timeout Idiom On Fri, 10 Dec 2004 00:52:27 +0900 "Chuckl" wrote: > This idiom has been a decent shortcut for my work: > > require 'timeout' > > > def timeout?(sec) > begin > freq = [0.01, sec / 1000].max > timeout(sec) { > while true > return false if yield > sleep(freq) > end > } > rescue Timeout::Error > return true > end > end > > > Code police may even approve, since 'timeout.rb' kinda uses > exception-throwing as flow control. > > Some little style improvements. Note that you automatically have a codeblock in a function, so you can spare the extra begin - end. Also there is a loop function that makes while(true) explicit. A personal style thing is, that I like to use { } for blocks whose return value is of interest, and do end blocks for blocks whose side-effects are of interest. require 'timeout' def timeout?(sec) freq = [0.01, sec / 1000].max timeout(sec) do loop do return false if yield sleep(freq) end end rescue Timeout::Error return true end [0.5, 0.9, 1.0, 2.0, 3.0].each do | sleep_time | result = timeout?(1) do sleep sleep_time end puts "While sleeping #{sleep_time}s #{result ? 'a' : 'no'} timeout occured." end Best regards, Brian PS: Unindented code is really hard to read. I only understood your code after using xemacs autoindentation. -- Brian Schr�der http://www.brian-schroeder.de/