示例:
class Base
@@var = "base"
def self.assign_var(var)
@@var = var
end
def self.show_var
@@var
end
def initialize
p @@var
end
end
class A < Base
assign_var("a")
end
class B < Base
assign_var("b")
end
class C < Base
assign_var("c")
end
p A.show_var # "c"
p B.show_var # "c"
p C.show_var # "c"
a = A.new # "c"
b = B.new # "c"
c = C.new # "c"
如何让他们在班上分配自己的价值?像这样:
p A.show_var # "a"
p B.show_var # "b"
p C.show_var # "c"
a = A.new # "a"
b = B.new # "b"
c = C.new # "c"
更新
我需要在初始化程序中访问此var。
class Base
@var = "base"
def self.assign_var(var)
@var = var
end
def self.show_var
@var
end
def initialize
p @var
end
end
class A < Base
assign_var("a")
end
class B < Base
assign_var("b")
end
class C < Base
assign_var("c")
end
p A.show_var # "a"
p B.show_var # "b"
p C.show_var # "c"
a = A.new # nil
b = B.new # nil
c = C.new # nil
如果我使用Vu的解决方案,那就不行了......有什么想法吗?
答案 0 :(得分:4)
类子变量未在子类中重新定义。在这种情况下,您可以使用类级别实例变量:
class Base
@var = "base"
def self.assign_var(var)
@var = var
end
def self.show_var
@var
end
end
class A < Base
assign_var("a")
end
class B < Base
assign_var("b")
end
class C < Base
assign_var("c")
end
p A.show_var # "a"
p B.show_var # "b"
p C.show_var # "c"
了解更多信息: http://www.railstips.org/blog/archives/2006/11/18/class-and-instance-variables-in-ruby/
答案 1 :(得分:2)
请将以下内容视为@Vu答案的延伸评论。他给出了一个很好的答案(+1),但故意保持接近OP的代码。我只想指出,通常的做法是使用类实例变量(如Vu所做的那样)和这些变量的访问器:
class Base
@var = "base"
class << self
attr_accessor :var
end
end
class A < Base
@var = "a"
end
class B < Base
self.var = "b"
end
Base.methods(false) #=> [:var, :var=]
A.methods(false) #=> []
A.methods.include?(:var) #=> true
A.method(:var=) #=> #<Method: A(Base)
A.method(:var).owner #=> #<Class:Base>
Base.instance_variables #=> [:@var]
A.instance_variables #=> [:@var]
Base.var #=> "base"
A.var #=> "a"
B.var #=> "b"
Base.var = 'cat'
Base.var #=> "cat"
A.var #=> "a"