Splat 运算符或正则表达式不起作用?

Splat operator or regex not working?

我是 Ruby 的新手,将下国际象棋作为一种学习练习。我正在尝试重构一些代码,但遇到了困难。

为什么这样做:

@available_moves = []

#part of castling logic
@available_moves << "c1" if empty?("b1") && empty?("c1") && empty?("d1")

def empty?(position)
  get_space(position).token =~ /_/
end
# sample tokens: "_e4", "ka2", "_b3"

...这不是吗?:

@available_moves = []

@available_moves << "c1" if emptyii?("b1", "c1", "d1")

def emptyii?(*positions)
  positions.each { |position| get_space(position).token =~ /_/ }
end

这可能是非常愚蠢的事情,但我不知道我做错了什么。

而不是使用each,使用all?来测试所有位置return true:

positions.all? { |position| get_space(position).token =~ /_/ }

positions.all? 仅当块 return 对每个位置都为真时才为真。

就您需要做什么而言,其他答案就在这里,但您应该了解为什么您当前的解决方案不起作用。

你走在正确的道路上,但你只需要更深入地观察你的逻辑。让我们考虑一下代码中的两行:

@available_moves << "c1" if empty?("b1") && empty?("c1") && empty?("d1")

这表示,“获取 c1 并将其放入 @available_moves 如果你得到 b1、c1 和 d1 的真值结果从空返回为真。这看起来不错并且显然有效。

但是,看看你的另一行出现问题的地方:

@available_moves << "c1" if emptyii?("b1", "c1", "d1")

这是说,"Shovel c1 into available_moves if...well, what exactly?"如果 b1 为真但 c1 和 d1 不是,您认为 emptyii 为真吗?如果只有所有这些都是真的,这是真的吗?到底是哪个?

在你的第一个例子中,你的表达非常清晰。然而,这不是。这就是为什么您会收到使用 .all? 的建议的原因,因为这对您要尝试做的事情更加清楚,而且当然会真正起作用(与您的声明相反)。