为什么在if语句内部的赋值不会在之前发生?

huangapple go评论46阅读模式
英文:

Why doesn't assignment inside an if statement not happen before?

问题

当我运行以下代码:

do_something(foo) if (foo = compute_foo).present?

我得到 `NameError: undefined local variable or method 'foo' for main:Object`。
我原以为条件(因此赋值)会在主命令之前被评估。

我在`irb`中尝试过这个问题,当我第二次运行这行代码时,命令就可以正常执行了... 所以赋值确实发生了,但是在`if`语句之后?这让我非常困惑,我希望能得到解释。

<hr>

*显然,这个错误可以通过不坚持使用一行代码来避免,但这不是我的问题。*
英文:

I have a piece of code that has to do something with an output from another (complex) function, but only if the result meets a condition. I thought I could make it a one-liner, but it didn't work, and I'm curious why.

When I run the following code:

do_something(foo) if (foo = compute_foo).present?

I get NameError: undefined local variable or method 'foo' for main:Object.
I was under the impression that the condition (thus the assignment) would be evaluated before the main command.

I tried playing with this in irb, and when I run the line a second time the command works... So the assignment does happen, but after the if statement? This got me very confused, and I was hoping for an explanation.

<hr>

Obviously this error could be avoided by simply not insisting in a one-liner, but that's not what I am asking.

答案1

得分: 3

当Ruby遇到这行代码do_something(foo) if (foo = compute_foo).present?时,它会从左到右开始评估它。

所以,在这种情况下,它首先遇到的表达式是do_something(foo)
但是,在这一点上,foo还没有被赋任何值,所以它会引发一个NameError,因为foo未定义。

正如Stefan提到的,这份文档将提供关于这个问题的清晰解释:

https://ruby-doc.org/3.2.2/syntax/control_expressions_rdoc.html#label-Modifier+if+and+unless.

英文:

Hi this is due to the order of execution

When the Ruby encounters this line do_something(foo) if (foo = compute_foo).present?, it will start evaluating it from left hand side to right hand side.

So, in this casee, the first expression it encounters is do_something(foo).
But, at this point, foo hasn't been assigned any value yet, so it raises a NameError because foo is undefined.

As Stefan mentioned, this doc will provide the clear explantion of this:

https://ruby-doc.org/3.2.2/syntax/control_expressions_rdoc.html#label-Modifier+if+and+unless.

huangapple
  • 本文由 发表于 2023年6月11日 20:40:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76450521.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定