Ruby looks for class variable in the Object instead of specific class

后端 未结 1 1202
耶瑟儿~
耶瑟儿~ 2021-01-07 06:33

This part works:

 class Example1
   @@var1= \"var1 in the Example1\"
   def get_var1
     @@var1
   end
 end

 example1 = Example1.new
 example1.get_var1
 #          


        
相关标签:
1条回答
  • 2021-01-07 06:41

    It appears as though the lexical scope for class variable lookup is kind of wacky. As near as I can tell, because you're not inside the

    class Example1
    end
    

    block, ruby doesn't look up @@var in your class, but rather from Object. If you want it explicitly from your class, you can do:

    def example1.get_var
        self.class.class_variable_get(:@@var1)
    end
    

    I stumbled across https://www.ruby-forum.com/topic/1228428 while searching for the answer. They're talking about 1.8.7, but it appears to apply to later versions as well.

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