2015-11-14 85 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