1

I would like some help with the following code:

sg = Fiber.new do
    s = 0
    loop do
        square = s * s
        s += 1
        s = Fiber.yield(square) || s
    end
end

puts sg.resume
puts sg.resume
puts sg.resume
puts sg.resume 40
puts sg.resume
puts sg.resume 0
puts sg.resume
puts sg.resume

When run, outputs:

0
1
4
1600
1681
0
1
4

How does line 6 s = Fiber.yield(square) || s work? I think I understand the component parts just not what the line as a whole is doing. (Is there an alternative way of writing this that might better help me understand?).

(Edit: This code is a very slightly modified example from page 295 'Beginning Ruby, From Novice to Professional 2nd Ed' by Peter Cooper.)

4

1 回答 1

2

根据文档yield

传递给 next 的任何参数resume都将是此Fiber.yield表达式计算的值。

线

s = Fiber.yield(square) || s

将传递给的参数分配resumes。如果该值是nil(或缺少参数),s则重新分配给s(即它不会改变)。

例子:

sg.resume       #=> s = nil || s
                #=> s = s

sg.resume 40    #=> s = 40  || s
                #=> s = 40

另一种写法是:

result = Fiber.yield(square)
s = result if result
于 2015-08-07T21:23:52.163 回答