2015-11-14 87 views
0

我遇到了麻煩,我的第一個條件,這將檢查,以確保添加的新件比它之前/之下的一個小。我的塔河內遊戲工作正常,直到我添加它。以下是我的代碼:河內塔,紅寶石條件

arrays = [[5,4,3,2,1],[],[]] 
win = false 

while win != true 
    puts "Choose a top piece: (1, 2, 3) " 
    top = gets.to_i 
    puts "Which stack to place this piece? (1, 2, 3)" 
    stack = gets.to_i 

    if (arrays[stack-1] == nil) || 
     (arrays[stack-1][arrays[stack-1].count-1] > arrays[top-1][arrays[top-1][arrays[top-1].count]]) 
    arrays[stack-1].push(arrays[top-1].pop) 
    else 
    "You need to follow the rules." 
    end 

    print arrays 
    if arrays[1] == [5,4,3,2,1] || arrays[2] == [5,4,3,2,1] 
    print "You're a winner!" 
    win = true 
    end 
end 
~ 

下面是我得到的錯誤。我如何執行我的檢查並以簡明的方式處理我的nil值數組?

towers_hanoi:13:in `[]': no implicit conversion from nil to integer (TypeError) 
     from towers_hanoi:13:in `<main>' 

回答

0

在if語句中有很多奇怪的事情正在進行。

肯定使用Array#empty?檢查數組是否爲空。一個空的數組不是零。

其次你的一些陣列包圍的是太令人費解,我不知道你正試圖在這裏完成的,但你肯定會被檢查,如果無>在某些情況下,號碼:

(arrays[stack-1][arrays[stack-1].count-1] > arrays[top-1][arrays[top-1][arrays[top-1].count]]) 

我懷疑這是你正在嘗試做什麼(因爲它會引發錯誤)。我會花一點時間考慮你的邏輯和重構。在河內的塔樓,你只需要擔心檢查你正在移動的那部分是否小於你要移動到的棧上的最後一部分(它代表頂部)。

使用Array#last,你將會找到更簡單的解決方案。

+0

謝謝!這非常有幫助。看起來我需要仔細看看Ruby文檔。 – Thrynn

1

使用empty?方法來確定數組是否爲空。僅供參考,不過,如果你想看到如果一個變量有nil值,使用nil?

此外,last方法將幫助噸這裏,並從輸入減去1馬上就會使代碼更易讀。試試這個:

arrays = [[5,4,3,2,1],[],[]] 
win = false 

while win != true 
    puts "Choose a top piece: (1, 2, 3) " 
    stack_from = gets.to_i - 1 
    puts "Which stack to place this piece? (1, 2, 3)" 
    stack_to = gets.to_i - 1 

    if (arrays[stack_to].empty?) || 
     (arrays[stack_to].last > arrays[stack_from].last) 
    arrays[stack_to].push(arrays[stack_from].pop) 
    else 
    "You need to follow the rules." 
    end 

    print arrays 
    if arrays[1] == [5,4,3,2,1] || arrays[2] == [5,4,3,2,1] 
    print "You're a winner!" 
    win = true 
    end 
end 
+0

我將我的代碼更改爲使用.empty?但我仍然遇到類似的錯誤。 這是錯誤: towers_hanoi.rb:13:in'>':Fixnum與nil的比較失敗(ArgumentError) from towers_hanoi.rb:13:'

' – Thrynn

+0

這是錯誤回調引用的行: (array [stack-1] [arrays [stack-1] .count-1]> arrays [top-1] [arrays [top-1] [arrays [top-1] .count]]) – Thrynn

+0

這是兩行。 – Jason