如何修复 Rubocop 中的 Style/MultipleComparison 攻击?
How to fix Style/MultipleComparison offense in Rubocop?
当我 运行 rubocop:
bin/main:70:6: C: Style/MultipleComparison: Avoid comparing a variable with multiple items in a conditional, use Array#include? instead.
我的代码:
if board1 == [1, 2, 3] || board1 == [4, 5, 6] || board1 == [7, 8, 9] ||
board1 == [3, 5, 7] || board1 == [1, 5, 9] || board1 == [1, 4, 7] ||
board1 == [2, 5, 8] || board1 == [3, 6, 9]
board1.each { |state| board_states[state - 1] = 'X' }
puts "#{player1} win"
break
end
我是 ruby 的新手,一般来说是编码方面的新手。如何按照 rubocop 的建议将上述代码重构得更简洁?
Rubocop 建议您使用 Array#include?
重构 if
条件。
states = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [3, 5, 7], [1, 5, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9]]
if states.include?(board1)
board1.each { |state| board_states[state - 1] = 'X' }
puts "#{player1} win"
break
end
当我 运行 rubocop:
bin/main:70:6: C: Style/MultipleComparison: Avoid comparing a variable with multiple items in a conditional, use Array#include? instead.
我的代码:
if board1 == [1, 2, 3] || board1 == [4, 5, 6] || board1 == [7, 8, 9] ||
board1 == [3, 5, 7] || board1 == [1, 5, 9] || board1 == [1, 4, 7] ||
board1 == [2, 5, 8] || board1 == [3, 6, 9]
board1.each { |state| board_states[state - 1] = 'X' }
puts "#{player1} win"
break
end
我是 ruby 的新手,一般来说是编码方面的新手。如何按照 rubocop 的建议将上述代码重构得更简洁?
Rubocop 建议您使用 Array#include?
重构 if
条件。
states = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [3, 5, 7], [1, 5, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9]]
if states.include?(board1)
board1.each { |state| board_states[state - 1] = 'X' }
puts "#{player1} win"
break
end