Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

trace - How to track the execution process of ruby program

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...