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

前端之家收集整理的这篇文章主要介绍了如何在Ruby中的字符串“A :: B :: C”中获取类对象?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以下示例失败 @H_301_2@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可以演变成

@H_301_2@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

解决方法

@H_301_19@ 您必须自己手动“分析”冒号,并在父模块/类上调用const_get: @H_301_2@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.

猜你在找的Ruby相关文章