我可以为我的排序实现一个超时方法,如下所示:
def timed_sort(seconds=1, &block)
Timeout::timeout(seconds) { quick_sort &block }
rescue Timeout::Error
raise Exception.new( "The process timed out")
end
然而,为了改善我的编码风格(主要是为了重新使用),我试图为这样的超时创建一个通用类,所以我可以调用:
a = [1,4,2,5]
a.timed_out(1).quick_sort
我目前的尝试是:
Class Array
def self.timed_out(seconds = 10)
Timer.new(self, seconds)
end
End
class Timer
attr_reader :seconds, :object
def initialize(object, seconds)
@seconds = seconds
@object = object
end
def method_missing(name, *args, &block)
Timeout::timeout(seconds) { object.send(name, *args, &block) }
rescue Timeout::Error
raise StandardError.exception("The process timed out")
end
end
当我尝试拨打a.timed_out.quick_sort
时,我得到:
未定义的方法`timed_out'