4.6 Debugging

Basic debugging is a skill that every programmer must learn. When your program is malfunctioning and you do not have a clue where the error is located, you can use multiple puts statements to check the value of your variables at different times. Modify the code in Example 4-12 to use the assignment operator (=) instead of the comparison operator (<=) in the first conditional statement, as in Example 4-13.

Example 4-13. Debugging example 1
     1 puts "Enter the customer's age: "
     2 # Get an integer age value from the user
     3 age = gets.to_i
     4 
     5 # Determine the cost based on age
     6 case
     7 # '=' is assignment NOT equality test '=='
     8 when (age = 12) then
     9 	cost = 9
    10 when (age >= 65) then
    11 	cost = 12
    12 else
    13 	cost = 18
    14 end
    15 
    16 # Print out the final cost
    17 puts "Ticket cost: " + cost.to_s

If you run the example, it will not matter what age you input; it will always output the ticket cost as 9. This is because you are not comparing age to the integer 12 but instead assigning 12 to age, which is something that will evaluate to true. Edit the program to match Example 4-14.

Example 4-14. Debugging example 2
     1 puts "Enter the customer's age: "
     2 # Get an integer age value from the user
     3 age = gets.to_i
     4 # DEBUG
     5 puts age
     6 
     7 # Determine the cost based on age
     8 case
     9 # '=' is assignment NOT equality test '=='
    10 when (age = 12) then
    11 	cost = 9
    12 when (age >= 65) then
    13 	cost = 12
    14 else
    15 	cost = 18
    16 end
    17 # DEBUG
    18 puts age
    19 
    20 # Print out the final ...

Get Computer Science Programming Basics in Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.