Use Timeout.
best_result = 0
begin
timeout(5) do
while true
new_result = rand
best_result = new_result if new_result > best_result
end
end
rescue Timeout::Error
puts "That's enough. Result is #{best_result}"
end
This effectively does the same thing you are doing (execute in another thread, thread gets dead after 5 seconds), but abstracts the timeout handling from your code. And it's in standard library.