Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby can not access variable outside the method?

Tags:

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:

undefined local variable or method 'template' for main:Object (NameError)

It seems that I can not access the template and result variable inner the generateMethods method?

Why?


Update:

It seems that the scope concept is differ from what is in the javascript?

var xx='xx';
function afun(){
  console.info(xx);
}

The above code will work.

like image 343
hguser Avatar asked Feb 22 '12 05:02

hguser


2 Answers

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.

like image 199
David Xia Avatar answered Nov 01 '22 13:11

David Xia


You are declaring local variables, not global ones. See this site for more (simplified) details: http://www.techotopia.com/index.php/Ruby_Variable_Scope

like image 22
DRobinson Avatar answered Nov 01 '22 13:11

DRobinson