对象由 Continuation
生成,在 +require+d Kernel#callcc
continuation
之后。它们拥有一个返回地址和执行上下文,允许从程序中的任何位置非本地返回到
块的末尾。延续有点类似于 C 的callcc
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
相关用法
- Ruby Continuation.cont[args, ...]用法及代码示例
- Ruby Continuation.call用法及代码示例
- Ruby Complex.to_f用法及代码示例
- Ruby Complex.magnitude用法及代码示例
- Ruby Comparable.between?用法及代码示例
- Ruby Coverage.peek_result用法及代码示例
- Ruby Complex.rectangular用法及代码示例
- Ruby Complex.cmp - numeric用法及代码示例
- Ruby Complex.fdiv用法及代码示例
- Ruby Complex.polar用法及代码示例
- Ruby Complex.arg用法及代码示例
- Ruby Complex.conj用法及代码示例
- Ruby Complex类用法及代码示例
- Ruby Complex.infinite?用法及代码示例
- Ruby Complex.abs用法及代码示例
- Ruby Complex.cmp / numeric用法及代码示例
- Ruby Complex conjugate()用法及代码示例
- Ruby Complex.cmp ==用法及代码示例
- Ruby Complex denominator用法及代码示例
- Ruby Complex.imaginary用法及代码示例
- Ruby Complex.cmp * numeric用法及代码示例
- Ruby Complex.rect用法及代码示例
- Ruby Complex.inspect用法及代码示例
- Ruby Complex abs用法及代码示例
- Ruby Complex.rationalize用法及代码示例
注:本文由纯净天空筛选整理自ruby-lang.org大神的英文原创作品 Continuation类。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。