Ruby 方法与块链接 - 令人困惑的不一致语法错误

发布于 2024-12-09 23:19:25 字数 886 浏览 0 评论 0原文

所以,我认为我很聪明,我向 Object 添加了一个这样的方法:

class Object
  def apply_if(cond)
    if cond
      yield self
    else
      return self
    end
  end
end

这(我认为)允许我有条件地向方法链添加位,这大大简化了我的 ActiveRecord 查询操作。但它给出了一个语法错误,我可以将其减少为以下代码:

data = [1,2,3,4,5]
results = data.
  apply_if(true and false) do |q|
    q + [0,0]
  end

同样,此错误:

results = data.apply_if(true and false){|q| q + [0,0]}

但这有效:

results = data.apply_if ((true and false)) {|q| q + [0,0]}

正如:

results = data.apply_if (true && false) {|q| q + [0,0]}

我发现其中的差异都与运算符优先级有关,但是运算符的优先级如何一对括号内重要吗?

为什么这里有语法错误?我没有看到任何可能的语法歧义,并且此方法在形状上与 Array#reduce 方法相同。

我在这里尝试了多种组合 - 带调用的显式块参数、方法定义内的各种类型的显式优先级。使用 lambda 代替块效果很好,但对于我的目的来说显然太笨重了。

So, thinking I'm all clever, I add a method like this to Object:

class Object
  def apply_if(cond)
    if cond
      yield self
    else
      return self
    end
  end
end

This (I thought) allows my to conditionally add bits to a method chain, which simplifies my ActiveRecord query manipulation quite a bit. But it gives a syntax error, which I can reduce down to the following code:

data = [1,2,3,4,5]
results = data.
  apply_if(true and false) do |q|
    q + [0,0]
  end

Likewise this errors:

results = data.apply_if(true and false){|q| q + [0,0]}

But this works:

results = data.apply_if ((true and false)) {|q| q + [0,0]}

As does:

results = data.apply_if (true && false) {|q| q + [0,0]}

I see that the differences there are all to do with operator precendence, but how can the precedence of an operator inside a pair of parentheses matter?

Why is there a syntax error here at all? I don't see any likely syntactic ambiguities, and this method is identical in shape to the Array#reduce method.

I've tried a number of combinations here - explicit block parameters with calls, various types of explicit precedence inside the method definition. Using a lambda instead of a block worked fine, but is obviously too clunky to use for my purposes.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

羁拥 2024-12-16 23:19:25

这与您的任何代码无关 - 参数列表中不允许使用 and 运算符。至于为什么,你必须询问核心团队,但在我看来,最明显的可能性是它存在的理由(具有极低的优先级)在参数列表中不起作用。

This has nothing to do with any of your code — the and operator just isn't allowed in an argument list. As for why, you'd have to ask the Core team, but the most obvious possibility IMO is that its raison d'etre (having extremely low precedence) doesn't work in an argument list.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文