当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Ruby Module.const_source_location用法及代码示例


本文简要介绍ruby语言中 Module.const_source_location 的用法。

用法

const_source_location(sym, inherit=true) → [String, Integer]
const_source_location(str, inherit=true) → [String, Integer]

返回包含指定常量定义的 Ruby 源文件名和行号。如果未找到命名常量,则返回nil。如果找到常量,但无法提取其源位置(常量在 C 代码中定义),则返回空数组。

inherit 指定是否在mod.ancestors 中查找(默认为true)。

# test.rb:
class A         # line 1
  C1 = 1
  C2 = 2
end

module M        # line 6
  C3 = 3
end

class B < A     # line 10
  include M
  C4 = 4
end

class A # continuation of A definition
  C2 = 8 # constant redefinition; warned yet allowed
end

p B.const_source_location('C4')           # => ["test.rb", 12]
p B.const_source_location('C3')           # => ["test.rb", 7]
p B.const_source_location('C1')           # => ["test.rb", 2]

p B.const_source_location('C3', false)    # => nil  -- don't lookup in ancestors

p A.const_source_location('C2')           # => ["test.rb", 16] -- actual (last) definition place

p Object.const_source_location('B')       # => ["test.rb", 10] -- top-level constant could be looked through Object
p Object.const_source_location('A')       # => ["test.rb", 1] -- class reopening is NOT considered new definition

p B.const_source_location('A')            # => ["test.rb", 1]  -- because Object is in ancestors
p M.const_source_location('A')            # => ["test.rb", 1]  -- Object is not ancestor, but additionally checked for modules

p Object.const_source_location('A::C1')   # => ["test.rb", 2]  -- nesting is supported
p Object.const_source_location('String')  # => []  -- constant is defined in C code

相关用法


注:本文由纯净天空筛选整理自ruby-lang.org大神的英文原创作品 Module.const_source_location。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。