2015-08-20 17 views
0

我是通过克里斯·派恩的Learn to Program读,我遇到了Chapter 10: Blocks and Procs这个奇怪的代码片段:这个while循环的条件是什么?

def doUntilFalse firstInput, someProc 
    input = firstInput 
    output = firstInput 

    while output 
    input = output 
    output = someProc.call input 
    end 

    input 
end 

buildArrayOfSquares = Proc.new do |array| 
    lastNumber = array.last 
    if lastNumber <= 0 
    false 
    else 
    array.pop       # Take off the last number... 
    array.push lastNumber*lastNumber # ...and replace it with its square... 
    array.push lastNumber-1   # ...followed by the next smaller number. 
    end 
end 

什么正在检查的条件,在上述while循环?它似乎不是while output == true的简写。

+0

Ruby教程不遵循Ruby的命名约定。我希望他在书中解决这个问题...... – spickermann

回答

2

while output表示运行循环,直到具有除falsenil以外的任何值。和Ruby一样,除了这两者之外,一切都是真实的价值。

+0

但是,那么它是不是等于输出==真?但是,当我用后者运行代码时,我得不到相同的结果。 –

+0

'output while == true'只有当'output = true'时才是true。但是如果'output = 1'呢?你的情况变得虚假。然而,在'while output'的情况下,对于'output = 1'它仍然成立(truthy)。因此有所不同。 – shivam

+0

啊,现在我明白了!谢谢! :) –