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

时间:2014-02-16 11:38:01

标签: ruby trace execution

我是ruby的新手,当我对某些程序感到困惑时,我想跟踪ruby程序的执行过程。我想知道是否有办法帮助我跟踪shell脚本set -x做什么?

PS:

如shell脚本test.sh:

set -x
ls /home
echo "hello dujun and haotianma!"

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

+ ls /home
dujun  haotianma
+ echo 'hello dujun and haotianma!'
hello dujun and haotianma!

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

1 个答案:

答案 0 :(得分:11)

我认为你可以使用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

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

(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)$ 

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

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

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

(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)$ 
相关问题