« Back to Blog

Rookie Programming Tips: Ruby and Pry

By Chris (Rain) Avila
May 14, 2018

If you’re a beginner looking to get into programming, there are a ton of great resources out there that I’m sure have been linked to somewhere on this blog before. Learn Python the Hard Way is a great resource that I used years ago to get my feet wet and start writing little scripts to help accomplish simple day-to-day activities that were painstakingly manual on their own. One of my earliest scripts was to generate tickets through the Zendesk API so we could send communications regarding company changes and have a record of the communications we generated.

While that was fun, debugging that code was a very trial-and-error process and at the time I didn’t know a better way to debug other than just running the code and fixing things every time it blew up. Then I got to know someone on our team here at Jungle Disk, Ryan, and it turned out he was a Ruby expert. I would never turning down an available resource so I started playing with Ruby. I found Ruby to be incredibly user-friendly but in the realm of debugging there is a Gem called Pry that both made it easier to solve problems I was having and help me understand the inner workings of what was happening in the code I was executing better.

Pry essentially lets you have a developer console at code runtime which allows you look at your code and actually see what’s going wrong. Writing a little script that will add one to an array of numbers and a then subtract two from the result of that as an example:

I’m getting back a result I don’t want:

The expected result would have add return [2, 3, 4, 5, 6, 7] and subtract return [0, 1, 2, 3, 4, 5]. So what’s going wrong? I’m going to put use pry to jump into the add_one method and try to figure out why my add_one class isn’t adding.

Looks like .each isn’t doing what I need it to do. Turns out .each has a return value of whatever was passed into it, so with Pry I can see .each isn’t going to work for what I’m trying to do. I can however use the .map method instead. So we will make the change:

And now, everything is working:

You wouldn’t ever really need to use Pry for a problem this simple in the real world and Pry is also so much more powerful than just the simple use case I’ve outlined here but hopefully you could see how Pry could make debugging complex problems much simpler.