如果语句可以重构为布尔运算符,如!=,==,&&和||?

Sea*_*zel 3 ruby refactoring if-statement boolean

可以将其重构为布尔值吗?board是一个数组,move是和索引。position_taken?(board, move)应该falseboard[move]is 或的情况下返回" ",但在is 或的情况下应返回。""niltrueboard[move]"X""O"

def position_taken?(board, move)
  if board[move] == " "
    false
  elsif board[move] == ""
    false
  elsif board[move] == nil
    false
  else
    true
  end
end
Run Code Online (Sandbox Code Playgroud)

per*_*won 7

Since you have less and simpler positive cases I would test for the opposite:

def position_taken?(board, move)
  %w[X O].include?(board[move])
end
Run Code Online (Sandbox Code Playgroud)

It will handle invalid values differently than your original approach but it does directly what the method name suggests: check if the position is taken (instead of checking if the position is not not taken).