puts and p
There are many kinds of bugs and consequently many ways to debug them. In this chapter we'll teach you some simple techniques you can use to isolate the bugs and understand where and why they are happening.
We'll start with the trusted
puts. We've already discussed them in the RubyMonk Ascent: More Classes chapter. Both
p serve similar purposes, but are slightly different. Typically
p is handy because it prints the output of inspecting the object which is more detailed than what
puts provides. For the sake of brevity, I'll just refer to
p in places where either
p makes sense.
Here is an exercise to demonstrate the use of
p. I've implemented a simple method that returns the name and age that you pass to it. But it is somehow not working. I suspect that the method expects data in a format different from what I'm sending it. You have to fix the method so that it prints the name and age from the parameter I pass to it.
That was easy, wasn't it?
Since we're on the topic of bugs, let me demonstrate a common bug the uninitiated is prone to make: dividing integers and expecting a float. Example time:
As you can see, dividing 6 by 2 gives 3, the correct result. The divident, divisor and quotient here are all integers. But what about 6/4 - it should yield 1.5, but it gave only 1, the integer part of the result. That is not what we typically expect - if you divide two numbers, you need the correct result - not just the integer part of the division.
This happens because Ruby converts the result to an integer - even if the result is not strictly an integer. Lets see how we can solve this using the
What did you learn from the above example? Integers in Ruby are of class
Fixnum, and numbers with decimals (which we call 'floating point numbers') are
Float. And of course, if you divide two numbers and expect the correct result with decimals, then at least one number in the operation must be a
Now, let's look at a slightly elaborate exercise. I've implemented the class
DrivingLicenseAuthority that decides whether to grant a license to applicants or not. But unfortunately, it is buggy. I'm not going to tell you all the details so you'll have to find out where things are breaking and why - the tests are pretty bland. The goal is to get all the tests to pass. Remember,
p is your friend.
Blindfolded, you may now debug this code!