2016-06-14 79 views
5

我有一個模塊,其中包含類名爲String(其中包括)。我需要按名稱查找類,並優雅地退後來,如果沒有這樣的類。是否有可能縮小紅寶石不斷查找

module Mod1 
    module String 
    end 
end 
Mod1.const_get 'String' 
#⇒ Mod1::String 
Kernel.const_get '::Mod1::String' 
#⇒ Mod1::String 

到目前爲止,這麼好。當我嘗試查找不存在的類時,我預計會收到NameError,這很好。問題是,如果沒有與現有的全局命名空間給定名稱一類,它被返回:

Mod1.const_get 'Fixnum' 
#⇒ Fixnum < Integer 
Kernel.const_get '::Mod1::Fixnum' 
#⇒ Fixnum < Integer 

我理解的原因,但我的問題是:有一個不折不扣的只能在給定名稱空間中查找常量的方法?

現在我請與

result.to_s.start_with?(namespace) 

的結果,但這絕對不是縮小查找奇的方式。

回答

7

答案是:

Mod1.const_get 'Fixnum', false 

這裏的DOC:

/* 
* call-seq: 
*  mod.const_get(sym, inherit=true) -> obj 
*  mod.const_get(str, inherit=true) -> obj 
* 
* Checks for a constant with the given name in <i>mod</i>. 
* If +inherit+ is set, the lookup will also search 
* the ancestors (and +Object+ if <i>mod</i> is a +Module+). 
* 
* The value of the constant is returned if a definition is found, 
* otherwise a +NameError+ is raised. 
* 
*  Math.const_get(:PI) #=> 3.14159265358979 
* 
* This method will recursively look up constant names if a namespaced 
* class name is provided. For example: 
* 
*  module Foo; class Bar; end end 
*  Object.const_get 'Foo::Bar' 
* 
* The +inherit+ flag is respected on each lookup. For example: 
* 
*  module Foo 
*  class Bar 
*   VAL = 10 
*  end 
* 
*  class Baz < Bar; end 
*  end 
* 
*  Object.const_get 'Foo::Baz::VAL'   # => 10 
*  Object.const_get 'Foo::Baz::VAL', false # => NameError 
* 
* If the argument is not a valid constant name a +NameError+ will be 
* raised with a warning "wrong constant name". 
* 
* Object.const_get 'foobar' #=> NameError: wrong constant name foobar 
* 
*/ 

https://github.com/ruby/ruby/blob/449fbfd4d4ce47be227804c22214fed32a5b0124/object.c#L2027

+1

完美,謝謝。明顯的建議「看看方法文檔」照常工作。 – mudasobwa

+0

我可能建議鏈接到文檔而不是MRI源? http://ruby-doc.org/core-2.3.1/Module.html#method-i-const_get –