2

I have a medhod like this.

def run
  loop do
    sleep 0.1
    # do something
  end
end

And I want to write it like this.

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

How can I write a method like this every?

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

I put sleep quantity; yield inside loop, then it works. Thanks, I couldn't figure out how to use yield.
You are welcome. I updated the answer with the loop. Please Vote it up if you like it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.