Not really a blog, just some stuff that a future me might need to remember one day.
Pry is a great replacement for irb and is very useful if you ever need to do any debugging. It does a lot. It’s sometimes hard to remember all the things it does especially when you don’t create bugs that often.
require 'pry'; binding.pry;
Run the program and it will stop with a prompt when it hits the
breakpoint. From here you can do everything that irb
does and more.
Pry has many commands that work like command line programs rather than Ruby methods. To get started and list the commands that are available in Pry and any installed plug-ins:
pry> help
or use the --help
option to get detailed help on any command:
pry> ls --help
If you want to just continue running your program from a breakpoint:
pry> exit
This will only run until the next breakpoint so if you are stuck in a loop and you really want to just stop the program you need:
pry> exit-program
or
pry> !!!
To get back to the code view
pry> whereami
or
pry> @
Sometimes you don’t see enough code, you can specify the line count either side of the breakpoint:
pry> @ 10
You need to include pry-backtrace
in your Gemfile, then it’s:
pry> pry-backtrace
Pry stores every command you input and you can view these using the hist
command:
[1] pry(main)> puts 'foo'
foo
=> nil
[2] pry(main)> hist
1: puts 'foo'
[3] pry(main)> puts 'foobar'
foobar
=> nil
[4] pry(main)> hist
1: puts 'foo'
2: hist
3: puts 'foobar'
[5] pry(main)>
edit
commandInputting short commands in Pry is pretty convenient but what if you want to input a multi-line command such as defining a new method or you want to edit a long command that mistyped?
Fortunately Pry integrates with your default editor via the edit
command. By default edit
will open up the last command in your editor
and then re-run it when you exit the editor after whatever changes you
made. This works best if you use a terminal hosted editor like Vim.
If you need to edit a command earlier than the last then use the hist
command to find out which line number it’s on and then use the `–in