在其他条件下假定为零的变量 [英] Variable in else condition assumed nil value

查看:54
本文介绍了在其他条件下假定为零的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在ruby 1.9.3中发现的奇怪现象.

This is something strange I've figured out in ruby 1.9.3.

这是代码:

>> r = true
>> if r
>>   a  = "hello"
>> else
>>   b = "hello"
>> end

现在a的值为"hello":

Now the value of a is "hello":

>> a
=> "hello"

奇怪的是b的值为nil

And strangely the value of b is nil

>> b
=> nil

由于b在场景中不存在,因此应取消声明.

Since b is nowhere in the scene, it should be undeclared.

为什么?

推荐答案

当解析器遇到 分配,而不是在分配发生时:

The local variable is created when the parser encounters the assignment, not when the assignment occurs:

=> foo
# NameError: undefined local variable or method `foo' for main:Object
=> if false
=>   foo = "bar" # does not assign to foo
=> end
=> nil
=> foo
=> nil

这篇关于在其他条件下假定为零的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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