Jeffrey Yong Jeffrey Yong - 10 months ago 58
Ruby Question

Proper Way of Debugging in Ruby

RubyAlgorithmsTest.rb:31:in `+': no implicit conversion of Array into String (TypeError)
from RubyAlgorithmsTest.rb:31:in `block in get_dependencies'
from RubyAlgorithmsTest.rb:29:in `each'
from RubyAlgorithmsTest.rb:29:in `get_dependencies'
from RubyAlgorithmsTest.rb:81:in `read_file'
from RubyAlgorithmsTest.rb:90:in `<main>'

I am very new to Ruby programming and I would like to know how I should decipher the error stack shown above. I am not sure how to tell which line the error first occurs. Do I read the stack chronologically? This is the GitHub repo for the code:

Answer Source

The error occurred on line 31. This is mostly always true, but there are times the actual problem occurs elsewhere and Ruby complains about it later. This is more common with syntax errors (missing end blocks for example). The next clue is + so look for where you are doing that. Looks like you are trying to concatenate an Array to a String which isn't allowed.

The rest of the stack trace tells you how you got to that line of code. So, the line 90 called line 81, called line 29, called line 31.

At this point you have a couple of options. You could put some puts dependencies.inspect and puts found_dependency.inspect above line 31 and see what it says.

Or you could use a tool like Pry (highly recommended!) and pause the program there to inspect it. To do this you need to:

  1. Install the gem via "gem install pry"
  2. At the top of your ruby file add these two lines:

    require 'rubygems' require 'pry'

  3. Just above line 31 add the line binding.pry

  4. Now run your program like normal.

When Ruby gets to your binding.pry line it will open up an IRB (technically Pry, but same sort of thing) prompt and you can inspect the code right there.

So you can simply type things like dependencies.class and it will return the result. It's great for poking around at your data right at that spot and figuring out what is wrong.