Custom Control Structures
Ruby’s use of blocks, coupled with its parentheses-optional syntax,
make it very easy to define iterator methods that look like and behave
like control structures. The loop
method of Kernel
is a simple example.
In this section we develop three more examples. The examples here use
Ruby’s threading API; you may need to read Threads and Concurrency to
understand all the details.
Delaying and Repeating Execution: after and every
Example 8-1 defines global methods named
after
and every
. Each takes a numeric argument that
represents a number of seconds and should have a block associated with
it. after
creates a new thread and
returns the Thread
object
immediately. The newly created thread sleeps for the specified number
of seconds and then calls (with no arguments) the block you provided.
every
is similar, but it calls the
block repeatedly, sleeping the specified number of seconds between
calls. The second argument to every
is a value to pass to the first invocation of the block. The return
value of each invocation becomes the value passed for the next
invocation. The block associated with every
can use break
to prevent any future
invocations.
Here is some example code that uses after
and every
:
require 'afterevery' 1.upto(5) {|i| after i { puts i} } # Slowly print the numbers 1 to 5 sleep(5) # Wait five seconds every 1, 6 do |count| # Now slowly print 6 to 10 puts count break if count == 10 count + 1 # The next value of count end sleep(6) # Give the above time to ...
Get The Ruby Programming Language now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.