2012-03-06 34 views
4

最多属性值直到最近,这就要用到精细工作:如何设置默认为一个模块类

module Demo 
    class << self 
    attr_accessor_with_default :x, "hey" 
    end 
end 

但是这不再是这种情况。

attr_accessor_with_default已被删除,我离开没有线索如何设置该属性的缺省值。

+0

HTTP: //stackoverflow.com/questions/7052509/how-to-do-attr-accessor-with-default-in-ruby – auralbee 2012-03-06 09:22:37

回答

4

对于普通的实例变量,你只是变量设置为默认值初始化里面。对于类的实例变量,你可以设置它的类体:

module Demo 
    class << self 
    attr_accessor :x 
    end 

    @x = "hey" 
end 
0

以下为我工作...

class Demo 
    attr_accessor :x 

    def initialize 
    @x= "hey" 
    end 
end 

然后,它可以被称为Demo.new.x =>hey

相关问题