I have a FUU constante inside Foo and Foo2 classes, and in order to DRY my code, I moved a method inside the BaseStuff superclass. Just like this:

class BaseStuff
  def to_s
    FUU
  end
end

class Foo < BaseStuff
  FUU = "ok"
end

class Foo2 < BaseStuff
  FUU = "ok2"
end

But my problem is that, after:

a = Foo.new
puts a.to_s

I get this error:

NameError: uninitialized constant BaseStuff::FUU

Is there a best practice to fix this?

有帮助吗?

解决方案

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

其他提示

class Foo < BaseStuff
  ::FUU = "ok"
end
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top