英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论