Rails and class variables

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

    Variables with @ are instance variables in ruby. If you're looking for class variables, they're prefixed with @@, so you should be using @@my_var = 123 instead.

    And the reason you can't use instance variables that way, is because if you define instance variables outside methods, they don't live in the same scope as your methods, but only live while your class is interpreted.

    var1 in your example is a local variable, which will only be visible inside the index method.

    Examples:

    class Foo
      @@class_variable = "I'm a class variable"
    
      def initialize
        @instance_variable = "I'm an instance variable in a Foo class"
        local_variable = "I won't be visible outside this method"
      end
    
      def instance_method_returning_an_instance_variable
        @instance_variable
      end
    
      def instance_method_returning_a_class_variable
        @@class_variable
      end
    
      def self.class_method_returning_an_instance_variable
        @instance_variable
      end
    
      def self.class_method_returning_a_class_variable
        @@class_variable
      end
    end
    
    Foo.new
    => #
    Foo.new.instance_method_returning_an_instance_variable
    => "I'm an instance variable in a Foo class"
    Foo.new.instance_method_returning_a_class_variable
    => "I'm a class variable"
    Foo.class_method_returning_an_instance_variable
    => nil
    Foo.class_method_returning_a_class_variable
    => "I'm a class variable"
    

提交回复
热议问题