2017-01-31 47 views
0

這說明如下:試圖寫在對一個簡單的倒數循環用Ruby

數字Cruncher

收件採用一個數作爲參數 的方法如果該數量是大於20 計數從數字向下通過2的 如果號碼是從數小於20 計數減少1的 顯示的數字,因爲它們向下計數到0。

我已經寫了這個,但它沒有做它應該做的。任何幫助?

def num_cruncher(num) 
count = num 

until count == 0 do 
    if num > 20 
     puts count - 2 
    else 
     puts "#{count}" 
    end 
     count -= 1 
    end 
end 
+3

你總是隻在這裏倒數1。 'count - 2'不會改變'count'。無論'count'的值如何,每循環執行一次'count - = 1'。你的邏輯應該(1)檢查'count'的值並根據你想要的規則遞減它,然後(2)打印'count'的當前值。 – lurker

+1

當num爲20時會發生什麼? –

回答

1

你可以在這裏使用Numeric#step。事情是這樣的:

def num_cruncher n 
    s = n > 20 ? -2 : -1 
    n.step(by: s, to: 0).entries 
end 

num_cruncher 23 
#=> [23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1] 
+1

@EricDuminil偉大的想法,只是重構我的代碼(認爲這就是你的意思)。 –

+0

更詳細,但也許更清楚:'n.step(by:-2,to:0).entries'。讀者:[Enumerable#entries](http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-tries)與[Enumerable#to_a]相同(相同的C代碼)(http ://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-to_a)。 –

+0

@CarySwoveland好主意,用你的建議修改了我的答案。 –

2

這裏是你的代碼,以儘可能少的變化可能:

def num_cruncher(num) 
    count = num 

    until count < 0 do 
    puts count 
    if num > 20 
     count -= 2 
    else 
     count -= 1 
    end 
    end 
end 

num_cruncher(10) 
# 10 
# 9 
# 8 
# 7 
# 6 
# 5 
# 4 
# 3 
# 2 
# 1 
# 0 

num_cruncher(21) 
# 21 
# 19 
# 17 
# 15 
# 13 
# 11 
# 9 
# 7 
# 5 
# 3 
# 1 

由環路以外提取的if語句,代碼變得有點短:

def num_cruncher(num) 
    if num > 20 
    step = 2 
    else 
    step = 1 
    end 

    until num < 0 do 
    puts num 
    num -= step 
    end 
end 
+0

謝謝!現在非常清楚。 – user7496931