【问题标题】:Splat operator or regex not working?Splat 运算符或正则表达式不起作用?
【发布时间】:2015-06-22 00:46:18
【问题描述】:

我是 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

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

【问题讨论】:

    标签: ruby regex splat


    【解决方案1】:

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

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

    positions.all? 仅当块为每个位置返回 true 时才会为 true。

    【讨论】:

    • 就是这个。也就是说,我不确定我是否完全理解为什么每个都不起作用......我想我得稍微研究一下。
    • 每个方法的返回值是它正在迭代的列表。所以该方法调用的返回值为["b1", "c1", "d1"]
    • 这意味着if emptyii? 永远为真。
    • ...因为非零/非假被评估为真。
    【解决方案2】:

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

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

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

    这说,“如果你得到一个真值结果,b1、c1 和 d1 从空返回为真,则将 c1 放入 @available_moves 中。这看起来不错并且显然有效。

    但是,请查看您的另一行出现问题的地方:

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

    这就是说,“如果……嗯,究竟是什么?”将 c1 铲入 available_moves如果 b1 为真,但 c1 和 d1 不是,您是否认为 emptyii 为真?如果只有所有这些都是真的,这是真的吗?究竟是哪一个?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-30
      • 2021-06-04
      • 2013-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多