Ruby has a lot of classic drive architectures, such as enumerators and generators, and so on. This brief introduction to the concept of the generator. The generator is a function-generated object, or a method of generating an object. The continuum in Ruby can be used to complete the function of the generator. The continuum is obscure, In fact it is very simple, it has 3 features:
1. The CALLCC method will pass a contiguous object to the code block, and you can save the object;
2. When the call method of the continuum is invoked, the instruction stream jumps to the CALLCC method;
3. If you pass an object to the call method of the continuum, the CALLCC method returns the object, and CALLCC returns nil if the object is not passed.
We refer to the example code below and I add a comment. The code is used to generate the Fibonacci sequence and an ascending sequence. The two classes FIBG and INCG inherit the abstract event-driven logic of the "abstract class" G,g implementation builder, and the concrete class FIBG and INCG are used to complete the actual build logic, It's all in the code:
Copy Code code as follows:
#!/usr/bin/ruby
Require ' continuation '
#一个生成器 "Abstract" class
Class G
DEF initialize
Do_g
End
# @main_context is actually next ' exit ' and let next return the value of @main_context.call (v), which is the number generated
Def next
CALLCC do |c|
@main_context = C
@g_context. Call
End
End
Private
def Do_g
CALLCC do |c|
@g_context = C
Return
End
G_loop #虚方法, implemented by the actual concrete class, but called by G!
End
# @g_context The intrinsic drive that is actually G, it repeats itself back into the g_loop and generates new numbers.
def g (v)
CALLCC do |c|
@g_context = C
@main_context. Call (v)
End
End
End
#具体的生成器类, used to generate the Fibonacci sequence.
Class FIBG < G
Private
#具体类实现g_loop, how the actual generation must be determined by the specific class
#g_loop不能直接由FibG的实例对象调用, but driven by G.
def G_loop
G (1)
a,b=1,1
Loop do
G (b)
A,b=b,a+b
End
End
End
Class INCG < G
def initialize (inc_val=10)
Super ()
@inc_val = Inc_val
End
<span style= "FONT-SIZE:18PX;" ></span><pre name= "code" class= "Ruby" >private
def G_loop
X=0
Loop do
G (x+ @inc_val)
x+= @inc_val
End
End
End
f = fibg.new
100.times {printf '%d '% F.next}
Puts
i = Incg.new
100.times {printf '%d '% I.next}
Puts
i = incg.new (11)
100.times {printf '%d '% I.next}