如何从字符串“A :: B :: C”获取类对象在Ruby? [英] How do I get class-object from string "A::B::C" in Ruby?
本文介绍了如何从字符串“A :: B :: C”获取类对象在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
strong> UPDATE
有关上述主题的问题:
- 在字符串和类名之间转换
- < a href =http://stackoverflow.com/questions/1448670/ruby-stringto-class> Ruby String#to_class
- 在Ruby中按名称获取类?
- Cast between String and Classname
- Ruby String#to_class
- Get a class by name in Ruby?
最后一个给出了好的解决方案,可以演变成
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
:
You'll have to manually "parse" the colons yourself and call const_get
on the parent module/class:
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
。
Someone has written a qualified_const_get
that may be of interest.
这篇关于如何从字符串“A :: B :: C”获取类对象在Ruby?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文