我有一个模块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"
似乎任何类变量要么给我一个错误或者nil,除非我特别用模块名称来限定它。我认为使用include A
会阻止这种情况。如何导出这些类变量,以便我可以直接引用它们two
而不必使用A.two
?
答案 0 :(得分: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