这是一个简单的示例,展示了我如何在代码中跟踪位置。如果我需要知道模块中的位置:
class Foo
attr_reader :initialize_loc
def initialize
@initialize_loc = [__FILE__, __LINE__]
# do more stuff...
end
end
如果我需要知道发生了什么事情:
require_relative 't1'
foo = Foo.new
# do lots of stuff until you want to know where something was initialized.
puts 'foo initialized at %s:%s' % foo.initialize_loc
当我运行代码时,我得到:
FooBar:Desktop foobar ruby t2.rb
foo initilized at /Users/foobar/Desktop/t1.rb:4
如果我不想弄乱模块的源代码,并且希望调试器在我需要它时跳入,我会让调试器这样做:
require_relative 't1'
require 'ruby-debug'
debugger
foo = Foo.new
# do lots of stuff until you want to know where something was initilized.
puts 'foo initilized at %s:%s' % foo.initialize_loc
执行将停止,我将在紧随其后的行进入调试器debugger
:
[0, 9] in t2.rb
1 require_relative 't1'
2 require 'ruby-debug'
3
4 debugger
=> 5 foo = Foo.new
6 # do lots of stuff until you want to know where something was initilized.
7 puts 'foo initilized at %s:%s' % foo.initialize_loc
8
t2.rb:5
foo = Foo.new
(rdb:1)
一个简单的s
将“步入”我进入下一行代码,这将在initialize
块中Foo
:
(rdb:1) s
[-1, 8] in /Users/foobar/Desktop/t1.rb
1 class Foo
2 attr_reader :initialize_loc
3 def initialize
=> 4 @initialize_loc = [__FILE__, __LINE__]
5 # do more stuff...
6 end
7 end
8
/Users/foobar/Desktop/t1.rb:4
@initialize_loc = [__FILE__, __LINE__]
(rdb:1)
除此之外,使用诸如grep -rn target_to_find path_to_search
递归搜索目录并列出与目标匹配的行的文件名和行号之类的工具将大大有助于找到您要查找的内容。
或者,:vim /target_to_find/ path_to_search
从 Vim 内部使用将返回您要查找的文件。