我正在研究一个返回false或Array的方法。当我在另一个方法中调用此数组并尝试将其分配给变量时,我期望该变量具有false或返回的Array。
正在发生的事情是,当我将方法的结果分配给变量时,只会导致true或false而不是false或Array
我在调用的方法内部使用了pry方法来确定将要返回的内容。我已经确认会返回一个数组,然后进行额外的撬动,确定该变量仅在返回数组时设置为true
WIN_COMBINATIONS = [
[0,1,2],
[3,4,5],
[6,7,8],
[0,3,6],
[1,4,7],
[2,5,8],
[0,4,8],
[2,4,6]
]
def won?(board)
#for the purpose of this study, winner(board) returns nil or "X" or "O"
result = winner(board)
if result == nil
#if the result of winner is null, return false
return false
end
#return the array at location 0
return WIN_COMBINATIONS[0]
end
def play(board)
#i'm attempting to assign the return of the won? method to result
result = won?(board)
#when result is evaluated, when an array is being returned, result becomes true or false,
#rather than what I'd expect as false or an array
end
答案 0 :(得分:1)
最好坚持这样的约定,即以问号结尾的方法应返回true
或false
,这肯定是更惯用的红宝石。
在您的示例中,可能类似于
def won?(board)
!!winner(board)
end
然后在方法play
def play(board)
result = won?(board) ? WIN_COMBINATIONS[0] : false
# or a shorter one line
# result = won?(board) && WIN_COMBINATIONS[0]
end