Rails and class variables

后端 未结 3 743
耶瑟儿~
耶瑟儿~ 2020-12-09 06:57
class MainController < ApplicationController

  @my_var = 123
   def index
    var1 = @my_var
   end

   def index2
    var2 = @my_var
   end
end
<
3条回答
  •  攒了一身酷
    2020-12-09 07:24

    @my_var, in your sample code, is an instance variable on the class MainController. That is, it's a class-level instance variable, and not an instance-level instance variable. It exists in a totally different scope to the instance variable associated with an instance of the class.

    Within the body of your instance methods, index and index2, you are attempting to dereference an instance variable on an object that is an instance of class MainController, but you have not defined that instance variable anywhere, so you get back nil.

    If you want to use @my_var as a class-level instance variable, you can get its value from within an instance of the class like this:

    var1 = self.class.instance_variable_get(:@my_var)
    

    Class variables are indicated with a @@ prefix, and their use is not entirely encouraged. A couple of minutes with Google will tell you why.

提交回复
热议问题