Ruby can not access variable outside the method?

前端 未结 3 1337
甜味超标
甜味超标 2021-01-03 22:44

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:


templat         


        
相关标签:
3条回答
  • 2021-01-03 23:14

    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.

    0 讨论(0)
  • 2021-01-03 23:15

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

    0 讨论(0)
  • 2021-01-03 23:33

    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.

    0 讨论(0)
提交回复
热议问题