Ruby 局部变量未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9671259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby local variable is undefined
提问by Sergii Shevchyk
I have the following Ruby code:
我有以下 Ruby 代码:
local_var = "Hello"
def hello
puts local_var
end
hello
I get the following error:
我收到以下错误:
local_variables.rb:4:in 'hello': undefined local variable or method 'local_var'
for main:Object (NameError) from local_variables.rb:7:in '<main>'
I always thought that local variables are not accessible from outside of the block, function, closure, etc.
我一直认为局部变量不能从块、函数、闭包等外部访问。
But now I defined local variable in the file and try to get an access from the function INSIDEthe same file.
但是现在我在文件中定义了局部变量并尝试从同一个文件中的函数内部获取访问权限 。
What's wrong with my understanding?
我的理解有什么问题?
回答by emre nevayeshirazi
In Ruby local variables only accessible in the scope that they are defined. Whenever you enter/leave a Class, a Module or a Method definiton your scope changes in Ruby.
在 Ruby 中,局部变量只能在定义的范围内访问。每当你进入/离开一个类、一个模块或一个方法定义你的范围在 Ruby 中发生变化。
For instance :
例如 :
v1 = 1
class MyClass # SCOPE GATE: entering class
v2 = 2
local_variables # => ["v2"]
def my_method # SCOPE GATE: entering def
v3 = 3
local_variables # => ["v3"]
end # SCOPE GATE: leaving def
local_variables # => ["v2"]
end # SCOPE GATE: leaving class
These entering and leaving points are called Scope Gates. Since you enter through Scope Gate via method definition you cannot access your local_varinside hellomethod.
这些进入和离开点称为范围门。由于您通过方法定义通过 Scope Gate 进入,因此您无法访问local_var内部hello方法。
You can use Scope Flattening concept the pass your variable through these gates.
您可以使用 Scope Flattening 概念将您的变量通过这些门。
For instance instead of using deffor defining your method you can use Module#define_method.
例如,def您可以使用Module#define_method.
local_var = "Hello"
define_method :hello do
puts local_var
end
In the same way you can define your classes via Class#Newso that your scope does not change when you pass through class definition.
以同样的方式,您可以通过定义您的类,Class#New以便在您通过类定义时您的范围不会改变。
local_var = 'test'
MyClass = Class.new do
puts local_var #valid
end
instead of
代替
class MyClass
puts local_var #invalid
end
In the same way you should use Module#Newif you want to pass your local variables through Module gates.
Module#New如果您想通过模块门传递局部变量,则应以同样的方式使用。
Example is taken from Metaprogramming Ruby
回答by J?rg W Mittag
local_varis a local variable. Local variables are local to the scope they are defined in. (That's why they are called"local variables", after all!) So, obviously, since local_varis defined in the script scope, you cannot access it in the method scope.
local_var是局部变量。局部变量在它们定义的范围内是局部的。(这就是为什么它们被称为“局部变量”,毕竟!)所以,很明显,由于local_var是在脚本范围内定义的,你不能在方法范围内访问它。

