如何通过Ruby父类调用子类定义的常量?
- 内容介绍
- 文章标签
- 相关推荐
本文共计159个文字,预计阅读时间需要1分钟。
在Ruby中,可以从父类访问子类的常量。以下是如何实现这一点的代码示例:
rubymodule Foo BASE_CONST='常量值'end
class Base include Foo
def test puts BASE_CONST endend
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 这似乎有效 – 它强制不断查找范围到当前实例的类
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'
本文共计159个文字,预计阅读时间需要1分钟。
在Ruby中,可以从父类访问子类的常量。以下是如何实现这一点的代码示例:
rubymodule Foo BASE_CONST='常量值'end
class Base include Foo
def test puts BASE_CONST endend
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 这似乎有效 – 它强制不断查找范围到当前实例的类
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'

