Ruby 无法访问方法外的变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9389432/
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 can not access variable outside the method?
提问by hguser
I am new to Ruby, and it seems that Ruby does support variables defined outside the method being accessed just now when I want to do something:
我是 Ruby 新手,似乎 Ruby 确实支持在我想做某事时在刚刚访问的方法之外定义的变量:
template=<<MTEMP
#methodName#:function(){},
MTEMP
result="";
def generateMethods(mds)
mds.each do |md|
result+=template.gsub(/#methodName#/,md).to_s+"\n";
end
result;
end
puts generateMethods(['getName','getAge','setName','setAge'])
When I tried to run it I got the error:
当我尝试运行它时,出现错误:
undefined local variable or method 'template' for main:Object (NameError)
main:Object (NameError) 的未定义局部变量或方法“模板”
It seems that I can not access the templateand resultvariable inner the generateMethodsmethod?
似乎我无法访问方法内部的template和result变量generateMethods?
Why?
为什么?
Update:
更新:
It seems that the scope concept is differ from what is in the javascript?
似乎范围概念与javascript中的概念不同?
var xx='xx';
function afun(){
console.info(xx);
}
The above code will work.
上面的代码会起作用。
采纳答案by David Xia
The resultand templatevariables inside the generateMethodsfunction are different from the ones declared outside and are local to that function. You could declare them as global variables with $:
该result和template内部变量generateMethods函数是从那些不同的外部声明,并局部的功能。您可以使用以下命令将它们声明为全局变量$:
$template=<<MTEMP
#methodName#:function(){},
MTEMP
$result="";
def generateMethods(mds)
mds.each do |md|
$result+=$template.gsub(/#methodName#/,md).to_s+"\n";
end
$result;
end
puts generateMethods(['getName','getAge','setName','setAge'])
But what's your purpose with this function? I think there's a cleaner way to do this if you can explain your question more.
但是您使用此功能的目的是什么?如果您能更多地解释您的问题,我认为有一种更简洁的方法可以做到这一点。
回答by DRobinson
You are declaring local variables, not global ones. See this site for more (simplified) details: http://www.techotopia.com/index.php/Ruby_Variable_Scope
您正在声明局部变量,而不是全局变量。有关更多(简化)详细信息,请参阅此站点:http: //www.techotopia.com/index.php/Ruby_Variable_Scope
回答by J?rg W Mittag
Local variables are local to the scope they are defined in. That's why they are called localvariables, after all!
局部变量在定义它们的范围内是局部的。这就是为什么它们被称为局部变量,毕竟!
Ergo, you cannot access them from a different scope. That's the whole pointof local variables.
因此,您无法从不同的范围访问它们。这就是局部变量的全部意义所在。

