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

Ruby:访问类的常量,例如类

发布时间:2020-12-17 01:30:33 所属栏目:百科 来源:网络整理
导读:我有一个类似于以下的类: class Foo MY_CONST = "hello" ANOTHER_CONST = "world" def self.get_my_const Object.const_get("ANOTHER_CONST") endendclass Bar Foo def do_something avar = Foo.get_my_const # errors here endend 获取const_get未初始化的
我有一个类似于以下的类:

class Foo
  MY_CONST = "hello"
  ANOTHER_CONST = "world"

  def self.get_my_const
    Object.const_get("ANOTHER_CONST")
  end
end

class Bar < Foo
  def do_something
    avar = Foo.get_my_const # errors here
  end
end

获取const_get未初始化的常量ANOTHER_CONST(NameError)

假设我只是在Ruby范围内做一些愚蠢的事情.我正在我正在测试此代码的机器上使用Ruby 1.9.3p0.

解决方法

工作中:

class Foo
  MY_CONST = "hello"
  ANOTHER_CONST = "world"

  def self.get_my_const
    const_get("ANOTHER_CONST")
  end
end

class Bar < Foo
  def do_something
    avar = Foo.get_my_const
  end
end

Bar.new.do_something # => "world"

你的下面部分不正确:

def self.get_my_const
    Object.const_get("ANOTHER_CONST")
end

在get_my_const方法中,self是Foo.所以删除对象,它会工作..

(编辑:李大同)

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

    推荐文章
      热点阅读