如何定义新的循环函数

时间:2014-03-23 02:51:04

标签: ruby loops

我有这样的方法。

def run
  loop do
    sleep 0.1
    # do something
  end
end

我想这样写。

def run
  every 100, :msec do
    # do something
  end
end

如何编写像every这样的方法?

1 个答案:

答案 0 :(得分:2)

def every(quantity, units = :sec)
  # this could be improved but you get the idea
  quantity = quantity / 1000.0 if units == :msec
  loop do 
    sleep quantity
    yield
  end
end

every 100, :msec do
  puts Time.now
end