我在FUU
和Foo
类中有一个Foo2
constan,为了干掉我的代码,我在BaseStuff
超类中移动了一个方法。就像这样:
class BaseStuff
def to_s
FUU
end
end
class Foo < BaseStuff
FUU = "ok"
end
class Foo2 < BaseStuff
FUU = "ok2"
end
但我的问题在于:
a = Foo.new
puts a.to_s
我收到此错误:
NameError:未初始化的常量BaseStuff :: FUU
有解决此问题的最佳做法吗?
答案 0 :(得分:3)
class Foo < BaseStuff
::FUU = "ok"
end
答案 1 :(得分:2)
class BaseStuff
FUU = nil
def to_s
self.class::FUU
end
end
class Foo < BaseStuff
FUU = "ok"
end
class Foo2 < BaseStuff
FUU = "ok2"
end
a = Foo.new
puts a.to_s # => ok
puts Foo2.new.to_s # => ok2