Ruby variable assignment in a conditional “if” modifier

前端 未结 2 1922
孤城傲影
孤城傲影 2020-12-21 15:39

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

I use this quite often:

return foo if (foo = bar.some_method)

w

相关标签:
2条回答
  • 2020-12-21 15:55

    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.

    0 讨论(0)
  • 2020-12-21 16:05

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

    0 讨论(0)
提交回复
热议问题