Ruby variable assignment in a conditional “if” modifier

与世无争的帅哥 提交于 2019-11-28 09:32:52

问题


I have a question about how the Ruby interpreter assigns variables:

I use this quite often:

return foo if (foo = bar.some_method)

where some_method returns an object or nil.

However, when I try this:

return foo if (true && (foo = bar.some_method))

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?


回答1:


Read it carefully :

Another commonly confusing case is when using a modifier if:

p a if a = 0.zero?

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.

The confusion comes from the out-of-order execution of the expression. First the local variable is assigned-to then you attempt to call a nonexistent method.

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.




回答2:


You could do return foo||=nil if foo = bar.some_method.



来源:https://stackoverflow.com/questions/21740291/ruby-variable-assignment-in-a-conditional-if-modifier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!