在self.method中看起来像@my_variable的实例变量是什么意思?

时间:2016-08-27 02:18:07

标签: ruby

我不明白类方法中的实例变量是做什么的。下面的代码对我没有意义。类方法如何操作实例变量?我甚至可以在没有实例的情况下调用类方法。

def self.schema
    return @schema if @schema
    DB.table_info(table) do |row|
      @schema[row['name']] = row['type']
    @schema
end    

编辑:@ Aetherus回答后跟进问题 以下代码示例中的first_name是什么?为什么我不能将它作为类变量访问,因为它在类范围内?为什么所有3种方法都会给我错误?

   class Person
     #class scope
      first_name = "jimmy"

       # expected error beacuse it would treat as local variable
      def print_name
        #instance scope
       first_name
      end

       #to my understanding this should work, but it doesnt. i dont know why
      def print_name_2
        #instance scope
        #with self.class i should be able to access class scope?
        self.class.first_name
      end  

      #to my understading this should work, but it doesnt. I dont know why.   
      def self.print_name
        #class scope
        #inside class scope, i should able to access first_name?
        first_name
       end

    end

1 个答案:

答案 0 :(得分:2)

简而言之,这些实例变量属于类,而不属于该类的实例。

要理解它,您需要了解有关Ruby的更多信息。

类是对象

在Ruby中,所有类都只是Class类型的对象。

String.class  #=> Class
Array.class   #=> Class
Class.class   #=> Class

您可以通过实例化Class

来定义匿名类
foo = Class.new do
  # Here you can define methods
end

foo.new  #=> an instance of an anonymous class

因为类是对象,所以它们也可以包含实例变量。

范围之门

触发范围转换有4个关键字:moduleclassdefdo(用于块)。在这里,我只显示classdef

# in the scope of main

class Foo
  # in the scope of Foo

  def self.bar
    # still in the scope of Foo
  end

  # in the scope of Foo

  def bar
    # in the scope of an instance of Foo
  end

  # back to the scope of Foo again
end

# back to the scope of main

范围中定义的实例变量属于该范围的当前对象(a.k.a。self)。在前面的示例中,如果您在Foo范围内定义实例变量,则该实例变量属于该范围的self,即类Foo

相关问题