如何跟踪ruby程序的执行过程

dj1*_*008 4 ruby trace execution

我是ruby的新手,当我对某些程序感到困惑时,我想跟踪ruby程序的执行过程.我想知道是否有一种方法可以像shell脚本set -x那样帮助我跟踪?

PS:

比如shell脚本test.sh:

set -x
ls /home
echo "hello dujun and haotianma!"
Run Code Online (Sandbox Code Playgroud)

当我执行test.sh时,输出将如下:

+ ls /home
dujun  haotianma
+ echo 'hello dujun and haotianma!'
hello dujun and haotianma!
Run Code Online (Sandbox Code Playgroud)

就像这个bash脚本在执行它之前回应每个语句一样,我想让Ruby程序显示哪些语句正在执行.

Aru*_*hit 13

我想你可以使用Ruby的stdlib Tracer.

我在我的test.rb文件中写了一个代码:

require 'tracer'

Tracer.on

class A
  def square(a)
    @b = a*a
    result
  end
  def result
    @b
  end
end

a = A.new
puts a.square(5)

Tracer.off
Run Code Online (Sandbox Code Playgroud)

现在运行代码,看看幕后发生了什么:

(arup~>Ruby)$ ruby test.rb
#0:test.rb:5::-: class A
#0:test.rb:5::C: class A
#0:test.rb:6::-:   def square(a)
#0:test.rb:10::-:   def result
#0:test.rb:13::E: end
#0:test.rb:15::-: a = A.new
#0:test.rb:16::-: puts a.square(5)
#0:test.rb:6:A:>:   def square(a)
#0:test.rb:7:A:-:     @b = a*a
#0:test.rb:8:A:-:     result
#0:test.rb:10:A:>:   def result
#0:test.rb:11:A:-:     @b
#0:test.rb:12:A:<:   end
#0:test.rb:9:A:<:   end
25
#0:test.rb:18::-: Tracer.off
(arup~>Ruby)$ 
Run Code Online (Sandbox Code Playgroud)

再看一下代码.现在我改变了跟踪点.

require 'tracer'

class A
  def square(a)
    @b = a*a
    result
  end
  def result
    @b
  end
end

Tracer.on

a = A.new
puts a.square(5)

Tracer.off
Run Code Online (Sandbox Code Playgroud)

现在运行代码,看看幕后发生了什么:

(arup~>Ruby)$ ruby test.rb
#0:test.rb:15::-: a = A.new
#0:test.rb:16::-: puts a.square(5)
#0:test.rb:4:A:>:   def square(a)
#0:test.rb:5:A:-:     @b = a*a
#0:test.rb:6:A:-:     result
#0:test.rb:8:A:>:   def result
#0:test.rb:9:A:-:     @b
#0:test.rb:10:A:<:   end
#0:test.rb:7:A:<:   end
25
#0:test.rb:18::-: Tracer.off
(arup~>Ruby)$ 
Run Code Online (Sandbox Code Playgroud)