条件“if”中的Ruby变量赋值。修改 [英] Ruby variable assignment in a conditional "if" modifier
问题描述
我有一个关于Ruby解释器如何分配变量的问题:
I have a question about how the Ruby interpreter assigns variables:
我经常使用这个:
return foo if (foo = bar.some_method)
其中some_method返回一个对象或nil。
where some_method returns an object or nil.
然而,当我尝试这个时:
However, when I try this:
return foo if (true && (foo = bar.some_method))
I get:NameError:未定义的局部变量或方法foo for main:Object。
I get: NameError: undefined local variable or method foo for main:Object.
导致第二行出错的第一行和第二行之间的评估差异是什么?
What is the difference in evaluation between the first and second lines that causes the second line to error?
推荐答案
仔细阅读:
另一个常见的令人困惑的情况是在使用修饰符时:
p a if a = 0.zero?
而不是打印 true
您收到 NameError,未定义的局部变量或方法'a'。由于 Ruby 首先解析左边的
,如果
,还没有看到赋值到它假定您希望调用方法。然后,Ruby将赋值视为 a
,并假设您引用本地方法
。
Rather than printing true
you receive a NameError, "undefined local variable or method 'a'". Since Ruby parses the bare a
left of the if
first and has not yet seen an assignment to a it assumes you wish to call a method. Ruby then sees the assignment to a
and will assume you are referencing a local method
.
混淆来自 表达式 的无序执行。 首先分配局部变量 - 然后你试图调用一个不存在的方法。
如你所说 - 无返回foo if(foo = bar.some_method)
和返回foo if(true&&(foo = bar.some_method))
将起作用,我打赌你,如果你没有在此行之前定义 foo
,那就不行了。
As you said - None return foo if (foo = bar.some_method)
and return foo if (true && (foo = bar.some_method))
will work, I bet you, it wouldn't work, if you didn't define foo
before this line.
这篇关于条件“if”中的Ruby变量赋值。修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!