Ruby local variable is undefined

前端 未结 2 2060
温柔的废话
温柔的废话 2020-12-01 04:59

I have the following Ruby code:

local_var = \"Hello\"

def hello
  puts local_var
end

hello

I get the following error:

loc         


        
相关标签:
2条回答
  • 2020-12-01 05:46

    In Ruby local variables only accessible in the scope that they are defined. Whenever you enter/leave a Class, a Module or a Method definiton your scope changes in Ruby.

    For instance :

    v1 = 1
    
    class MyClass # SCOPE GATE: entering class
      v2 = 2
      local_variables # => ["v2"]
    
      def my_method # SCOPE GATE: entering def
        v3 = 3
        local_variables  # => ["v3"]
      end # SCOPE GATE: leaving def
    
      local_variables # => ["v2"]
    end # SCOPE GATE: leaving class
    

    These entering and leaving points are called Scope Gates. Since you enter through Scope Gate via method definition you cannot access your local_var inside hello method.


    You can use Scope Flattening concept the pass your variable through these gates.

    For instance instead of using def for defining your method you can use Module#define_method.

    local_var = "Hello"
    
    define_method :hello do
      puts local_var
    end
    

    In the same way you can define your classes via Class#New so that your scope does not change when you pass through class definition.

    local_var = 'test'
    
    MyClass = Class.new do
      puts local_var #valid
    end
    

    instead of

    class MyClass
      puts local_var #invalid
    end
    

    In the same way you should use Module#New if you want to pass your local variables through Module gates.

    Example is taken from Metaprogramming Ruby

    0 讨论(0)
  • 2020-12-01 05:55

    local_var is a local variable. Local variables are local to the scope they are defined in. (That's why they are called "local variables", after all!) So, obviously, since local_var is defined in the script scope, you cannot access it in the method scope.

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