Rails and class variables

后端 未结 3 745
耶瑟儿~
耶瑟儿~ 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:18

    Because code executes in different context. You can see here:

    class MainController
      puts self
      def print_self
        puts self
      end
    end
    #=> MainController
    MainController.new.print_self #=> 
    

    As you can see in first print the self is MainController, in second print the self is the object which derived from MainController class.

    In the assignment to @my_vay this variable belongs to MainController, and in the second cases, the @my_var belongs to object (not a class) and these varaibles are different.

提交回复
热议问题