How to track the execution process of ruby program

2020-02-06 08:21发布

问题:

I am new to ruby and I want to track the execution process of ruby program when I feel confused about some programs. I wonder whether there is a way to help me track just as shell scripts set -x do?

PS:

Such as shell script test.sh:

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

when I execute test.sh, then the output will be like:

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

Just as how this bash script echos each statement before executing it, I want to make a Ruby program show which statements are executing.

回答1:

I think you can use the Ruby's stdlib Tracer.

I wrote a code in my test.rb file :

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

Now run the code, and see all what's going on under the hood :

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

Again look at the code. Now I changed trace point.

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

Now run the code, and see all what's going on under the hood :

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