How to track the execution process of ruby program

后端 未结 1 952
一向
一向 2020-12-11 07:29

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

相关标签:
1条回答
  • 2020-12-11 08:02

    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)$ 
    
    0 讨论(0)
提交回复
热议问题