Ruby:从父类访问调用子类常量?

时间:2014-08-25 22:16:52

标签: ruby oop

在Ruby中,如何从父类访问调用类的常量?

Module Foo
  class Base
    def test()
      #how do I access calling class's constants here?
      #ex: CallingClass.SOME_CONST
    end
  end
end

class Bar < Foo::Base
  SOME_CONST = 'test'
end

2 个答案:

答案 0 :(得分:7)

这似乎有效 - 它强制不断查找范围到当前实例的类

module Foo
  class Base
    def test
      self.class::SOME_CONST
    end
  end
end

class Bar < Foo::Base
  SOME_CONST = 'test'
end

Bar.new.test # => 'test'

答案 1 :(得分:0)

如果你想获得子类中定义的所有常量及其值,你可以这样做:

module Foo
  class Base
    def test
      constants = self.class.constants
      constants.zip(constants.map { |c| self.class.const_get(c) }).to_h
    end
  end  
end

class Bar < Foo::Base
  SOME_CONST    = 'test'
  ANOTHER_CONST = 'quiz'
end

Bar.new.test #=> {:SOME_CONST=>"test", :ANOTHER_CONST=>"quiz"}