在ruby中定义一个等于nil的索引并返回false [英] Define an index in ruby equal to nil and return false
问题描述
我正在尝试定义一种方法,该方法检查电路板上的给定空间是否为空,并解决了符合文字不等于空格的场景。
我的测试未能产生false / true,而是提供了nil。
什么我试过了:
board = [,,,,,,, ,]
def position_taken?(董事会,指数)
如果董事会[index] == [] ||没有
假装
elsif board [index]!= []
put true
end < br $> b $ b结束
结束
I am trying to define a method that checks if a given space on the board is empty and address the scenarios that qualify as an empty space that isn't equal to the literal " ".
My tests failed to produce false/true, and instead provided nil.
What I have tried:
board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
def position_taken?(board, index)
if board[index] == [" "] || nil
puts false
elsif board[index] != [" "]
puts true
end
end
end
推荐答案
我的测试未能产生false / true,而是提供了nil。
My tests failed to produce false/true, and instead provided nil.
原因是你的代码没有涵盖所有情况。
尝试这样的事情:
The reason is that your code do not cover all cases.
Try something like this:
board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
def position_taken?(board, index)
if board[index] == [" "] || nil # not sure what this is supposed to be
puts false
elsif board[index] != [" "]
puts true
else
# put a warning message here and you will have surprise
end
end
end
原因是 board [index] == [] || nil
和 board [index]!= []
不是补充条件。
如果第二个条件应该作为第一个补充,代码应该简单:
The reason is that board[index] == [" "] || nil
and board[index] != [" "]
are not complementary conditions.
In case second condition should be complement of first, the code should be simply:
board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
def position_taken?(board, index)
if board[index] == [" "] || nil
puts false
elsif board[index] != [" "]
else
puts true
end
end
end
Nota:我有从未使用Ruby,我只知道其他语言的常用用法。
Nota: I have never used Ruby, I just know common usages in other languages.
def position_taken?(board,index)
if board [index] ==| | board [index] == nil || board [index] ==
返回false
elsif board [index]!=
返回true
结束
结束
感谢您的帮助,我最终发现这个解决方案有效,看看问题是怎么回事你解释了我的代码。
def position_taken?(board, index)
if board[index] == " " || board[index] == nil || board[index] == ""
return false
elsif board[index] != " "
return true
end
end
Thank you for your help, I ended up finding this solution worked and what the problem was by seeing how you interpreted my code.
这篇关于在ruby中定义一个等于nil的索引并返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!