2012-02-25 109 views
2

我有一个模块A:导出变量从模块

module A 
    extend self 
    attr_accessor :two, :four 
    ONE = "one" 
    @two = "two" 
    @three = "three" 
    @@four = "four" 
    @@five = "five" 
    def six 
    "six" 
    end 
end 

我需要它的另一个文件中:

require 'a' 
include A 
p ONE  # => "one" 
p two  # => nil 
p A.two # => "two" 
p three # => error 
p four # => nil 
p five # => error 
p six  # "six" 

好像任何类变量,要么给我一个错误或者零,除非我特别将其范围与模块名称。我认为使用include A会阻止。如何导出这些类变量,以便我可以直接将它们引用为two而不必使用A.two

回答

0

如果您在类/模块级别定义变量,那么它是一个类实例变量而不是实例变量。我们使用||=来设置getter方法,因为模块没有初始化方法;

module A 
    ONE = "one" 

    attr_writer :two 

    def two 
    @two ||= "two" 
    end 

    def three 
    @@three ||= "three" 
    end 

    def three=(val) 
    @@three = val 
    end 
end 

然后你可以直接使用方法;

include A 

p two 
p three 
two = 2 
three = 3 
p two 
p three