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

如何在Ruby中的字符串“A :: B :: C”中获取类对象?

发布时间:2020-12-16 22:34:11 所属栏目:百科 来源:网络整理
导读:以下示例失败 class A class B endendp Object.const_get 'A' # = Ap Object.const_get 'A::B' # = NameError: wrong constant name A::B UPDATE 有关该主题的问题: Cast between String and Classname Ruby String#to_class Get a class by name in Ruby?
以下示例失败
class A
  class B
  end
end
p Object.const_get 'A' # => A
p Object.const_get 'A::B' # => NameError: wrong constant name A::B

UPDATE

有关该主题的问题:

> Cast between String and Classname
> Ruby String#to_class
> Get a class by name in Ruby?

最后一个gives a nice solution可以演变成

class String
  def to_class
    self.split('::').inject(Object) do |mod,class_name|
      mod.const_get(class_name)
    end
  end
end

class A
  class B
  end
end
p "A::B".to_class # => A::B

解决方法

您必须自己手动“分析”冒号,并在父模块/类上调用const_get:
ruby-1.9.1-p378 > class A
ruby-1.9.1-p378 ?>  class B
ruby-1.9.1-p378 ?>    end
ruby-1.9.1-p378 ?>  end
 => nil 
ruby-1.9.1-p378 > A.const_get 'B'
 => A::B

有人写了一个可能感兴趣的qualified_const_get.

(编辑:李大同)

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

    推荐文章
      热点阅读