如果“if"出现,为什么条件语句和 ruby​​ 中的赋值会失败?语句在子句末尾? [英] Why does conditional statement and assigning value in ruby fails if the "if" statement is at end of clause?

查看:38
本文介绍了如果“if"出现,为什么条件语句和 ruby​​ 中的赋值会失败?语句在子句末尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么最后一个语句(语句末尾带有if (tmp2 = foo)")失败?

Why does the last statement (with "if (tmp2 = foo)" at the end of the statement) fail?

def foo;5;end

# this one works
if (tmp = foo)
  puts tmp.to_s
end

# why this one fails
puts tmp2.to_s if (tmp2 = foo) #=> undefined local variable or method ‘tmp2’ for main:Object

推荐答案

由于解析器的工作方式而失败.

It fails because of the way the parser works.

从解析器的角度来看,变量 tmp2 存在于代码中从它第一次被赋值的点到它超出范围的点.对于这一点,何时(或是否)实际执行赋值并不重要,只是在解析器看到赋值时(即它取决于代码中的赋值位置).

From the parser's point of view the variable tmp2 exists from the point in the code at which it is first assigned until the point where it goes out of scope. For this it does not matter, when (or if) the assignment is actually executed, just when the parser sees the assignment (i.e. it depends on the assignments position in the code).

扩展这一点:

名称是局部变量还是方法调用由解析器决定.解析器仅根据它是否已经看到对该变量的赋值来做出该决定.所以当解析器在看到 tmp2 = ... 之前看到 tmp2 时,它决定这里 tmp2 指的是一个方法.当该部分代码实际执行时,它会尝试调用不存在的方法 tmp2,因此您会收到错误消息.

The decision whether a name is a local variable or a method call is made by the parser. The parser makes that decision solely based on whether or not it has already seen an assignment to that variable. So when the parser sees tmp2 before seeing tmp2 = ..., it decides that here tmp2 refers to a method. When that part of the code is actually executed, it tries to call the method tmp2 which does not exist so you get the error.

这篇关于如果“if"出现,为什么条件语句和 ruby​​ 中的赋值会失败?语句在子句末尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆