instance and class variables in rails controller

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

    When you declare instance variable outside of method, you might not get the result you want. It is an instance variable, yes, but it belongs to the class itself (which is an instance of class Class).

    class Foo
      @myvar = "class-level"
    
      def initialize
        @myvar = 'instance-level'
      end
    end
    
    f = Foo.new
    
    f.class.instance_variable_get(:@myvar) # => "class-level"
    f.instance_variable_get(:@myvar) # => "instance-level"
    f.instance_variable_get(:@myvar2) # => nil 
    

    If you try to get value of uninitialized ivar, it will evaluate to nil. That's why you got nil in your experiments: the variable doesn't exist at that scope.

    To get instance-level variables, set them in methods/actions.

提交回复
热议问题