本文簡要介紹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 Module.const_set用法及代碼示例
- Ruby Module.const_missing用法及代碼示例
- Ruby Module.const_get用法及代碼示例
- Ruby Module.const_defined?用法及代碼示例
- Ruby Module.constants用法及代碼示例
- Ruby Module.class_variables用法及代碼示例
- Ruby Module.class_exec用法及代碼示例
- Ruby Module.class_variable_get用法及代碼示例
- Ruby Module.class_variable_defined?用法及代碼示例
- Ruby Module.class_eval用法及代碼示例
- Ruby Module.class_variable_set用法及代碼示例
- Ruby Module.attr_accessor用法及代碼示例
- Ruby Module.method_removed用法及代碼示例
- Ruby Module.private用法及代碼示例
- Ruby Module.deprecate_constant用法及代碼示例
- Ruby Module.instance_method用法及代碼示例
- Ruby Module.included_modules用法及代碼示例
- Ruby Module.singleton_class?用法及代碼示例
- Ruby Module.module_exec用法及代碼示例
- Ruby Module.included用法及代碼示例
- Ruby Module.include?用法及代碼示例
- Ruby Module.ruby2_keywords用法及代碼示例
- Ruby Module.module_eval用法及代碼示例
- Ruby Module.extend_object用法及代碼示例
- Ruby Module.autoload用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Module.const_source_location。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。