How do I get class-object from string “A::B::C” in Ruby?

后端 未结 3 1260

The following example fails

class A
  class B
  end
end
p Object.const_get \'A\' # => A
p Object.const_get \'A::B\' # => NameError: wrong constant name A::         


        
3条回答
  •  -上瘾入骨i
    2021-02-08 17:29

    Extlib provides a full_const_get method, which does just this.

    http://github.com/datamapper/extlib/blob/master/lib/extlib/object.rb#L67

    You could either include extlib, or copy this implementation and use it yourself (assuming the licensing is compatible with whatever you're using it for)

提交回复
热议问题