Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 查找作用域为特定命名空间(模块)的常量(类)_Ruby - Fatal编程技术网

Ruby 查找作用域为特定命名空间(模块)的常量(类)

Ruby 查找作用域为特定命名空间(模块)的常量(类),ruby,Ruby,我试图以编程方式获取常量(例如类),但只想查看在特定命名空间中定义的常量。但是,const_get在搜索常量时将冒泡到更高的名称空间。例如: module Foo class Bar end end class Quux end 如果然后要求Foo返回常量“Bar”,它将返回正确的类 Foo.const_get('Bar') #=> Foo::Bar 但是,如果您向它请求“Quux”,它将弹出其搜索路径并找到顶级Quux: Foo.const_get('Quux') #=&g

我试图以编程方式获取常量(例如类),但只想查看在特定命名空间中定义的常量。但是,
const_get
在搜索常量时将冒泡到更高的名称空间。例如:

module Foo
  class Bar
  end
end

class Quux
end
如果然后要求
Foo
返回常量
“Bar”
,它将返回正确的类

Foo.const_get('Bar')
#=> Foo::Bar
但是,如果您向它请求
“Quux”
,它将弹出其搜索路径并找到顶级Quux:

Foo.const_get('Quux')
#=> Quux
有没有办法让它只在调用
const\u get
的模块中进行搜索?

显示:

检查mod中具有给定名称的常量。如果设置了inherit,则查找还将搜索祖先(如果mod是模块,则查找对象)

如果找到定义,则返回常量的值,否则将引发NameError

然后,您可以执行以下操作:

module Foo
  class Bar
  end
end

class Quux
end

Foo.const_get('Quux',false) rescue NameError
# >> NameError
Foo.const_get('Bar',false) rescue NameError
# >> Foo::Bar
+1用于创建良好且清晰的问题。