Middle
How can you debug code without using a debugger?
sobes.tech AI
Answer from AI
Main methods of debugging without a debugger:
- Using
putsto output intermediate variable values and program flow. - Logging to a file using the standard
Loggerlibrary. - Applying methods that output information about an object, such as
#inspector#p. - Using exceptions to check certain conditions or program states.
- Reading stack trace messages when errors occur.
Example of using puts:
# Simple example with puts
def calculate_sum(a, b)
sum = a + b
puts "Value of a: #{a}" # Output the value of variable a
puts "Value of b: #{b}" # Output the value of variable b
puts "Calculated sum: #{sum}" # Output intermediate result
sum
end
result = calculate_sum(5, 10)
puts "Final result: #{result}"
Example of logging with Logger:
# Logging example
require 'logger'
# Create a logger for output to a file
log = Logger.new('application.log')
def process_data(data)
# Write info to log
log.info("Start processing data: #{data}")
processed_data = data.upcase
# Write processing result
log.debug("Data after processing: #{processed_data}")
processed_data
rescue => e
# Log error
log.error("Error processing data: #{e.message}")
nil
end
process_data("some input")
Example of using p and inspect:
# Using p and inspect
data = { name: "Alice", age: 30 }
p data # Uses inspect, outputs a more detailed view
puts data.inspect # Explicitly uses inspect
Example of using exceptions:
# Using exceptions to check
def divide(a, b)
raise ArgumentError, "Division by zero is not allowed" if b == 0
a / b
end
begin
result = divide(10, 0)
rescue ArgumentError => e
puts "An error occurred: #{e.message}" # Catch and handle the exception
end