instance and class variables in rails controller

后端 未结 5 1489
一整个雨季
一整个雨季 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:46

    Classes are also objects in Ruby, so they can have their own instance variables which are called class instance variables.

    • @@world is a class variable
    • @insworld is a class instance variable
    • #index is an instance method

    When you try to access @insworld in #index, Ruby searches for the instance variable in the A object (meaning A.new) because #index is an instance method.

    But you defined @insworld as a class instance variable which means it is defined in the class object itself (meaning A).

    The following code demonstrates:

    class Hi
      @@a = 1 # class variable
      @b  = 2 # class instance variable
    
      def initialize
        @c = 3 # instance variable
      end
    
      def test # instance method, works on objects of class Hi
        puts @@a # => 1
        puts @b  # => nil, there is no instance variable @b
        puts @c  # => 3 # we defined this instance variable in the initializer
      end
    end
    
    Hi.class_variables        # => @@a
    Hi.instance_variables     # => @b
    Hi.new.instance_variables # => @c
    # Hi is an object of class Class
    # Hi.new is an object of class Hi
    

    Keep in mind that all instance variables return nil if they don't exist.

提交回复
热议问题