加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 01:33:58 所属栏目:百科 来源:网络整理
导读:在 Ruby中,如何从父类访问调用类的常量? Module Foo class Base def test() #how do I access calling class's constants here? #ex: CallingClass.SOME_CONST end endendclass Bar Foo::Base SOME_CONST = 'test'end 解决方法 这似乎有效 – 它强制不断查
在 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

解决方法

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

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'

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读