instance and class variables in rails controller

后端 未结 5 1437
一整个雨季
一整个雨季 2021-01-30 23:21

I\'m new to rails and ruby. I was studying the concept of class and instance variables. I understood the difference but when I tried it out using the controller in rails it got

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-30 23:51

    When you declare @instworld you are inside BooksController class (i.e. self will return BooksController. Weird thing in ruby is that classes are also objects (the are instances of class Class) hence you in fact declares instance variable @instworld for this particular instance of class Classm not for instance of BooksController.

    You can check it really easily by declaring class method:

    class A
      # self here returns class A
      @variable = 'class instance variable'
      @@variable = 'class variable'
    
      def initalize
        # self here returns the instance
        @variable = 'instance variable'
      end
    
      def self.test_me
        # self here returns class A
        @variable
      end
    
      def test_me
        # self returns the instance
        @variable
      end
    
      #class variable is accessible by both class and instance 
      def test_me2
        @@variable
      end
    
      def self.test_me2
        @@variable
      end
    end
    
    A.test_me       #=> 'class instance variable'
    A.new.test_me   #=> 'instance variable'
    A.test_me2      #=> 'class variable'
    A.new.test_me2  #=> 'class variable'
    

提交回复
热议问题