来自超类的未初始化常量

时间:2012-04-01 16:33:47

标签: ruby uninitialized-constant

我在FUUFoo类中有一个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

有解决此问题的最佳做法吗?

2 个答案:

答案 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