2012-07-22 71 views
2

作为一个实验,我写了一些代码,看起来像红宝石初始化实例变量以外的方法

class MyClass 

    @var = 100 

    def hello 
     p "hello" 
    end 

end 

我知道,如果我这样做MyClass.new@var没有那个对象上定义的,而我认为这将定义@var在类MyClass上。

这是否有实际用法?

回答

5

确实有一个用途:类变量。正常的Ruby类变量实现,@@超类及其子类之间的相同的变量:

class A 
    @@v = 0 
    def self.v; @@v; end 
    def self.v=(val); @@v=val; end 
end 
class B < A; end 
A.v #-> 0 
A.v= 3 #-> 3 
B.v #->3 
B.v= 42 #-> 42 
A.v #-> 42 

显然,这是没什么用(除了事实是,与类的实例变量,类变量也可以通过实例方法直接访问,而不是通过self.class)。但与类的实例变量相同的例子:

class A 
    @v = 0 
    def self.v; @v; end 
    def self.v=(val); @v=val; end 
end 
class B < A; end 
A.v #-> 0 
A.v= 3 #-> 3 
B.v= 42 #-> 42 
A.v #-> 3 

此外,类的实例变量可以利用所有已为实例变量写的元编程的,就像这样:

class Foo 
    class << self 
    attr_accessor :v #Uses a class instance variable 
    end 
end 
+0

你的第二个例子是行不通的,怎么你会在类接收器上调用实例方法吗? – kamal 2015-10-28 16:49:50

+0

@kamal:哎呦。固定! – Linuxios 2015-10-28 19:55:21

1

如果您为@var

MyClass.singleton_class.class_eval { attr_accessor :var } 

存取方法,那么你可以把@var像类变量。区别在于它不会被MyClass的子类继承。

_why利用这个在Dwemthy's Array