I understand everything that is happening in the following code except for the while output section:
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
I understand while for the most part but for some reason I can’t see the forest through the trees in this code. Could someone explain what is happening in the while output part between lines 5 and 8. I have no doubt it is extremely simple but I’ve hit a wall with it. Any help much appreciated.
outputwill become the return value of the proceduresomeProc, which is in turn passed as a parameter in line #28, asbuildArrayOfSquares. This, in turn, will returnfalsein a certain case; when this happens, thewhileloop will terminate.In detail,
firstInputis[5], which becomes the firstinput. We callbuildArrayOfSquareswith[5]. Since5is not<= 0, we take5out, put in25and4.Next iteration of while,
outputis[25, 4]. We continue. Back intobuildArrayOfSquares. Take4off the end; push in16, then3.outputis now[25, 16, 3].Next time,
outputis[25, 16, 9, 2]. Then[25, 16, 9, 4, 1]. Then[25, 16, 9, 4, 1, 0].And the next time,
0 <= 0, andbuildArrayOfSquaresreturnsfalseintooutput. The loop terminates.inputis still[25, 16, 9, 4, 1, 0], which is what we presumably wanted.