我不明白 ruby​​ 本地范围 [英] I don't understand ruby local scope

查看:45
本文介绍了我不明白 ruby​​ 本地范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个例子中,

def foo(x)
  if(x > 5)
    bar = 100
  end
  puts bar
end

然后 foo(6) 输出:100而 foo(3) 什么也不输出.

Then foo(6) Outputs: 100 and foo(3) outputs nothing.

但是,如果我将定义更改为

However if i changed the definition to

def foo(x)
  if(x > 5)
    bar = 100
  end
  puts bob
end

我收到未定义的局部变量或方法"错误.

I get an "undefined local variable or method" error.

所以我的问题是为什么当我调用 foo(3) 并且 bar 从未设置时我没有收到此错误?

So my question is why I am not getting this error when I call foo(3) and bar is never set?

推荐答案

这里发生了一些事情.首先,在 if 块中声明的变量与在方法顶层声明的变量具有相同的局部作用域,这就是为什么 barif 之外可用的原因.其次,您收到该错误是因为 bob 被直接引用.Ruby 解释器从未见过它,也从未见过它被初始化.然而,它已经看到 bar 之前在 if 语句中初始化.所以当它到达酒吧时它知道它存在.将这两者结合起来,这就是你的答案.

There a couple of things going on here. First, variables declared inside the if block have the same local scope as variables declared at the top level of the method, which is why bar is available outside the if. Second, you're getting that error because bob is being referenced straight out of the blue. The Ruby interpreter has never seen it and never seen it initialized before. It has, however, seen bar initialized before, inside the if statement. So when is gets to bar it knows it exists. Combine those two and that's your answer.

这篇关于我不明白 ruby​​ 本地范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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