當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。