Ruby 局部变量作用域 [英] Ruby local variable scope

查看:56
本文介绍了Ruby 局部变量作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 ruby​​ 中的变量范围而苦苦挣扎.我的印象是局部变量可以通过它们下面的方法访问.看看下面的代码,但是我收到了一个未定义的变量错误.

I'm struggling with variable scope in ruby. I was under the impression that local variables were accessible by methods below them. Looking at the following code however I'm getting an undefined variable error.

a = Array.new

def testing()
  a.push("test")
end

testing

使用全局变量效果很好,如何避免使用全局变量?

Using global variables it works just fine, how can I avoid using global variables?

推荐答案

这里没什么好说的,只是 Ruby 中的局部变量只能在定义它们的范围内访问,以及在其中定义的任何块(闭包)捕获它们的范围.因为在 Ruby 中,与其他一些动态语言不同,方法不是闭包,它们不捕获局部变量.

There isn't much to say here except that local variables in Ruby are only accessible in the scope in which they are defined and any blocks (closures) defined in that scope that capture them. Since in Ruby, unlike some other dynamic languages, method are not closures, they do not capture local variables.

如果您尝试过,请说:

irb(main):001:0> a = 3
=> 3
irb(main):002:0> define_method(:testing) do
irb(main):003:1*   puts a
irb(main):004:1> end
=> :testing
irb(main):005:0> testing
3

它有效,因为代码在块中而不是在方法中.

It works, since the code is in a block instead of a method.

这篇关于Ruby 局部变量作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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