20

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.

Chuck
  • 998
  • 8
  • 17
  • 30
hguser
  • 35,079
  • 54
  • 159
  • 293

4 Answers4

16

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.

David Xia
  • 5,075
  • 7
  • 35
  • 52
  • In fact,I just want to generate some methods in javascript according to the function name. – hguser Feb 22 '12 at 11:01
  • @hguser it is not recommended in ruby to use global variables, like you know its not recommended in javascript to avoid naming conflicts, find better way to handle your variables than declaring them global – bjhaid Feb 23 '12 at 16:45
2

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

DRobinson
  • 4,441
  • 22
  • 31
0

You need to use global variables(with $) or constants (all capital letters or the first and some of them)

You can search more of this here

Second R
  • 11
  • 2
-11

Local variables are local to the scope they are defined in. That's why they are called local variables, after all!

Ergo, you cannot access them from a different scope. That's the whole point of local variables.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • 44
    It works differently in Javascript (and Python), presumably the OP's source of confusion. Your answer would be more helpful if you didn't act like Ruby's way of doing things is self evident. – Antimony Apr 17 '13 at 03:06
  • Antimony: Yes, this also slightly confused me as a newcomer to Ruby. One could also define the variable as a constant if this is the correct semantic. Then the variable is accessible within the OP's method. – stephanmg May 22 '19 at 15:08