1

我了解以下代码中发生的所有内容,但该部分除外while output

1 def doUntilFalse firstInput, someProc
2  input  = firstInput
3  output = firstInput
4  
5  while output
6    input  = output
7    output = someProc.call input
8  end
9  
10  input
11 end
12 
13 buildArrayOfSquares = Proc.new do |array|
14  lastNumber = array.last
15  if lastNumber <= 0
16    false
17  else
18    array.pop                         #  Take off the last number...
19    array.push lastNumber*lastNumber  #  ...and replace it with its square...
20    array.push lastNumber-1           #  ...followed by the next smaller number.
21  end
22 end
23
24 alwaysFalse = Proc.new do |justIgnoreMe|
25  false
26 end
27
28 puts doUntilFalse([5], buildArrayOfSquares).inspect

我大部分都理解while,但由于某种原因,我无法通过这段代码中的树木看到森林。有人可以解释while output第 5 行和第 8 行之间发生了什么。我毫不怀疑它非常简单,但我已经碰壁了。非常感谢任何帮助。

4

1 回答 1

1

output将成为过程的返回值,该过程someProc又作为参数传递给第 #28 行,如buildArrayOfSquares. 反过来,这将false在某种情况下返回;发生这种情况时,while循环将终止。

详细来说,firstInputis [5],它变成了第一个input。我们buildArrayOfSquares用调用[5]。由于5is not <= 0,我们5取出,放入25and 4

while 的下一次迭代output[25, 4]。我们继续。回到buildArrayOfSquares. 脱掉4末端;推入16,然后3output现在是[25, 16, 3]

下一次,output[25, 16, 9, 2]。然后[25, 16, 9, 4, 1]。然后[25, 16, 9, 4, 1, 0]

下一次,0 <= 0buildArrayOfSquares返回。循环终止。is still ,这可能是我们想要的。falseoutputinput[25, 16, 9, 4, 1, 0]

于 2012-05-19T17:36:44.660 回答