0

Is it possible to debug dynamically defined method in Ruby? If so, how can I achieve it?

So I opened a new Pry session and first tried it like this:

require "byebug"

def hello(x)
  byebug
  x += 1
  puts x
end

hello(5)

It shouted at me with "*** No sourcefile available for (pry)". I was still able to step through the code, but I couldn't see the source.

Then I tried doing it like this:

def hello(x)
  binding.pry
  x += 1
  puts x
end

hello(5)

And now it's the other way round: I am able to see the source code, but I can't step through the code (when I type "step" it shouts at me with "NameError: undefined local variable or method `step' for main:Object"). Looks like Pry actually does have the needed source, but the debugger doesn't work unfortunately :(

I managed to do it in Python repl using IPython (It didn't work in standard Python repl though):

def hello(x):
    breakpoint()
    x += 1
    print(x)

hello(5)

I would love to be able to achieve the same in Ruby

Bo Yi
  • 123
  • 1
  • 9
  • 1
    That's not dynamically defined. A dynamically defined method would be with, for example, `define_method`. – Tom Lord Apr 18 '19 at 14:05
  • 1
    And I cannot reproduce your `binding.pry` problem. That code works perfectly fine for me; I don't see any "undefined method `step`" error. What version of ruby and `pry` are you using? – Tom Lord Apr 18 '19 at 14:10
  • @TomLord: Thanks for pointing out that this can't be called "dynamically defined method". I thought that any method that is defined not in source code, but after program has started is called "a dynamically defined method" – Bo Yi Apr 18 '19 at 15:36
  • @TomLord also for some reason I am not able to reproduce the problem in my snippet with binding.pry either. I am not sure what I was doing wrong, but I have just tried running it now and it worked fine this time. However I still managed to find a place where binding.pry doesn't work for me as expected: https://pastebin.com/pAPDNyiM – Bo Yi Apr 18 '19 at 15:42
  • It worked fine for me when the code is in source file, but when I run it in Pry it does stop but there is no output at all, and when I type "frame" it says "NameError: undefined method `__pry__' for class `#>'" – Bo Yi Apr 18 '19 at 15:47
  • P.S. My version of Ruby is 2.5.1 and my version of Pry is "0.12.2" – Bo Yi Apr 18 '19 at 15:49

0 Answers0