如何从字符串“A :: B :: C”获取类对象在Ruby? [英] How do I get class-object from string "A::B::C" in Ruby?

查看:159
本文介绍了如何从字符串“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

有关上述主题的问题:


  1. 在字符串和类名之间转换

  2. < a href =http://stackoverflow.com/questions/1448670/ruby-stringto-class> Ruby String#to_class

  3. 在Ruby中按名称获取类?

  1. Cast between String and Classname
  2. Ruby String#to_class
  3. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆