2016-06-07 66 views
-2
def generator(from, to, step) 
    ary = [from] 
    nex = from += step 
    min = from += step 
    while from != to 
    if from < to 
     from += step 
     ary.push(nex) 
     nex += step 
    elsif from > to 
     from -= step 
     ary.push(min) 
     min -= step 
    else   
     return nil 
    end 
end 
return ary 
end 

有人可以幫我解釋爲什麼這只是返回到「to'element減2紅寶石從對階序

例如當 發生器(10,20,1),它會返回[10,11,12..18],而不是所有的方式將20

+1

壓痕做這樣的事情是理解你的代碼非常重要,尤其是當有很多事情就像你在這裏。在尋求幫助時儘量保持整潔有序。 – tadman

+0

你不能使用'(from..to).step(step).to_a'嗎? –

回答

2

變化

nex = from += step 
min = from += step 

nex = from + step 
min = from + step 

您的from已經因爲這個步驟而增加了兩次(所以它的循環比預期的要少)。

如果你想將它寫一行代碼,你可以使用Numeric#step

2.3.0 > 10.step(20).to_a 
#=> [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] 

2.3.0 > 20.step(10, -1).to_a 
#=> [20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10] 
+0

嗯。謝謝。您的解決方案適用於我給出的具體示例。但是當from是比to更高的數字時它不起作用。它留給我一個空白的數組。 –

+0

你的代碼的邏輯存在一些缺陷,如果你改成''ary.push(from)''而不是'nex''和''min'',那麼你應該會看到你期望的行爲''generator(20 ,10,1)''應該導致相反。我不得不提到,如果你提供了一個跳過你的''到''數字的步驟,那麼你將最終陷入無限循環。 –