Ruby 无法访问方法外的变量? [英] Ruby can not access variable outside the method?
问题描述
我是 Ruby 新手,看来 Ruby 确实支持在我想做某事时在刚刚访问的方法之外定义的变量:
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:
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:
main:Object (NameError) 的未定义局部变量或方法模板"
undefined local variable or method 'template' for main:Object (NameError)
似乎我无法访问 generateMethods
方法内部的 template
和 result
变量?
It seems that I can not access the template
and result
variable inner the generateMethods
method?
为什么?
更新:
作用域的概念似乎与 javascript 中的概念不同?
It seems that the scope concept is differ from what is in the javascript?
var xx='xx';
function afun(){
console.info(xx);
}
上面的代码会起作用.
推荐答案
generateMethods
函数中的 result
和 template
变量与那些在外部声明并且是该函数本地的.您可以使用 $
将它们声明为全局变量:
The result
and template
variables inside the generateMethods
function are different from the ones declared outside and are local to that function. You could declare them as global variables with $
:
$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.
这篇关于Ruby 无法访问方法外的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!