为什么我不能访问 Ruby 方法中的局部变量? [英] Why can't I access a local variable inside a method in Ruby?

查看:51
本文介绍了为什么我不能访问 Ruby 方法中的局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 test.rb 的 Ruby 文件

I have a Ruby file named test.rb

ff="ff"
def test
  puts ff
end

我执行它,出现错误:

test.rb:3:in `test': main:Object (NameError) 的未定义局部变量或方法 `ff'

这是什么原因?有什么文档可以解释吗?

What's the reason for this? Is there any documentation to explain it?

推荐答案

test 方法定义中无法访问 ff 的原因仅仅是方法(使用 def 关键字)创建一个新的范围.与分别使用 classmodule 关键字定义类和模块相同.

The reason ff is inaccessible inside the test method definition is simply that methods (created with the def keyword) create a new scope. Same with defining classes and modules using the class and module keywords respectively.

在这种情况下,main(顶级对象)的作用几乎与作用域问题完全无关.

The role of main (the top-level object) is almost completely irrelevant to the question of scope in this situation.

请注意,如果您确实希望 test 方法能够访问定义上下文中定义的局部变量,请使用 define_method(或者在您的情况下,<代码>define_singleton_method 方法),见这里:

Note that, if you DO want your test method to have access to locals defined in the definition context, then use the define_method (or in your case, the define_singleton_method method), see here:

ff = "hi"
define_singleton_method("test") { ff }
test #=> "hi"

def 关键字不同,define_method 方法系列不会创建新的作用域,而是关闭当前作用域,捕获任何局部变量.

Unlike the def keyword, the define_method family of methods do not create new scopes but instead close over the current scope, capturing any local variables.

在@soup 给出的下一个示例中使用 @ff 的原因不是 main 在某种程度上是一个特殊情况",它只是定义了一个 ivar顶级是 main 的一个 ivar,因此可以被在 main 上调用的方法访问.

The reason using @ff worked in the next example given by @soup, is not that main is somehow a "special case" it's just that an ivar defined at top-level is an ivar of main and so is accessible to a method invoked on main.

然而,test 方法与 main 的关系是什么?它不是on 的方法,只是main 本身——它实际上是一个定义在Object 类上的私有实例方法.这意味着 test 方法(作为私有方法)几乎可用于 ruby​​ 程序中的每个对象.定义在顶层 (main) 的所有方法实际上都定义为 Object 类上的私有实例方法.

What, however, is the relationship of the test method to main? It is not a method on just main itself - it is actually a private instance method defined on the Object class. This means that the test method would be available (as a private method) to nearly every object in your ruby program. All methods defined at top-level (main) are actually defined as private instance methods on the Object class.

有关 Ruby 顶级的更多信息,请参阅这篇文章:http://banisterfiend.wordpress.com/2010/11/23/what-is-the-ruby-top-level/

For more information on the Ruby top-level, see this article: http://banisterfiend.wordpress.com/2010/11/23/what-is-the-ruby-top-level/

这篇关于为什么我不能访问 Ruby 方法中的局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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