类 Continuation

Continuation 对象由 Kernel#callcc 生成,在 +require+ continuation 之后。它们保存返回地址和执行上下文,允许从程序中的任何位置非本地返回到 callcc 代码块的末尾。Continuation 有点类似于 C 的 setjmp/longjmp 的结构化版本(尽管它们包含更多状态,因此您可能会认为它们更接近于线程)。

例如

require "continuation"
arr = [ "Freddie", "Herbie", "Ron", "Max", "Ringo" ]
callcc{|cc| $cc = cc}
puts(message = arr.shift)
$cc.call unless message =~ /Max/

产生

Freddie
Herbie
Ron
Max

您也可以在其他方法中调用 callcc

require "continuation"

def g
  arr = [ "Freddie", "Herbie", "Ron", "Max", "Ringo" ]
  cc = callcc { |cc| cc }
  puts arr.shift
  return cc, arr.size
end

def f
  c, size = g
  c.call(c) if size > 1
end

f

这个(有点人为的)例子允许内部循环提前放弃处理

require "continuation"
callcc {|cont|
  for i in 0..4
    print "#{i}: "
    for j in i*5...(i+1)*5
      cont.call() if j == 17
      printf "%3d", j
    end
  end
}
puts

产生

0:   0  1  2  3  4
1:   5  6  7  8  9
2:  10 11 12 13 14
3:  15 16