Many errors in code written by developers at all levels boil down to just a few common types of problems:
Syntax: check brackets, if/elsif/else statements, braces, commas, parentheses, quotation marks, etc. The computer needs syntax to be exactly right in order for it to run your programs: it cannot make any assumptions about what you might mean. So it cannot, for example, infer “Wednesday” from “Wendesday.” Make sure you are using ruby syntax.
Variables: make sure your variable names are consistent and that they are defined before you use them for the first time. Name them in ways that convey their use so that others (and you!) remember what they are meant to do.
Functions: make sure that you know how your functions work. What kinds of things do they return? A string? An array? A hash?
If you get stuck, try the following to help you figure out what is going on:
Print out variable values at different points in the program to make sure they return what you expect.
Make sure the coloring in your text editor looks like you expect it to.
Read the error output in the terminal. It tries to be helpful, but it will often not quite point you towards the problem. It can at least give you a ballpark location in the code and some things to look for.
Get sections of the code working (see step one) so that you can narrow your search for the problem. irb can help with this: try playing in this environment to debug sections.
Read the ruby documentation for the methods you are employing.
Comment throughout your code to make sure you understand what every step is doing. This will help you pinpoint problems.
Ask for help!
These exercises will help you practice debugging your code. There are no problems: only solutions waiting to be found.
puts"Hello!"greeting=gets.chomp()ifgreeting["Arrr!"]puts"Go away, pirate."elsifputs"Greetings, hater of pirates!"end
Collections
Broken:
dickens=["Charles Dickens,""1870"]thackeray={"William Thackeray","1863"}trollope={'Anthony Trollope','1882'}hopkins=["Gerard Manley Hopkins"=>"1889"]defdied(array)name=array[2]year=array[1]puts"#name died in {year}."putsdied(Dickens)putsdied(thackeray)putdied(trollop)putsdied(hopkins)end
Fixed:
# Create a collection of these authors and# the year they kicked the bucket;# print the collection in the following format:# Charles Dickens died in 1870.# Charles Dickens, 1870# William Thackeray, 1863# Anthony Trollope, 1882# Gerard Manley Hopkins, 1889dickens=["Charles Dickens","1870"]thackeray=["William Thackeray","1863"]trollope=['Anthony Trollope','1882']hopkins=["Gerard Manley Hopkins","1889"]defdied(array)name=array[0]year=array[1]puts"#{name} died in #{year}."endputsdied(dickens)putsdied(thackeray)putsdied(trollope)putsdied(hopkins)
Branching
Broken:
# A time traveller has suddenly appeared in your classroom!# Create a variable representing the traveller's# year of origin (e.g., year = 2000)# and greet our strange visitor with a different message# if he is from the distant past (before 1900),# the present era (1900-2020) or from the far future (beyond 2020).puts"Greetings! What is your year of origin?'
origin == gets.chomp().to_i
if origin < 1900
puts 'That's the past!'
elseif origin > 1900 && origin < 2020
puts "That's the present!"
elsif
puts "That'sthefuture!"
Fixed:
# A time traveller has suddenly appeared in your classroom!# Create a variable representing the traveller's# year of origin (e.g., year = 2000)# and greet our strange visitor with a different message# if he is from the distant past (before 1900),# the present era (1900-2020) or from the far future (beyond 2020).puts"Greetings! What is your year of origin?"origin=gets.chomp().to_iiforigin<1900puts"That's the past!"elsiforigin>1900&&origin<2020puts"That's the present!"elseputs"That's the future!"end
Classes
Broken:
# Write a simple class that defines a person# with attributes of first_name, last_name# and has a method signature of to_s which# prints the object as "Jefferson, Thomas".classyPersondefinitial(fnamelname)@first_name=firstname@last_name==lnamedefto_s@last_name+," "+@first_nameendtj=Person.new("Thomas","Jefferson")putsperson.fnameputtj
# Calculating Grades (ok, let me think about this one)# Write a program that will average 3 numeric exam grades, return an average test score, a corresponding letter grade, and a message stating whether the student is passing.# Average Grade# 90+ A# 80-89 B# 70-79 C# 60-69 D# 0-59 F# Exams: 89, 90, 90# Average: 90# Grade: A# Student is passing.# Exams: 50, 51, 0# Average: 33# Grade: F# Student if failsput"Input exam grade one:"exam_one=gets.chomp().toiputs'Input exam grade two:'exam_two=gets.chomp(.to_sputs"Input exam grade three:"exam_3=gets.chomp().to_ideflist_grade(exam_oneexam_twoexam_three)puts"Exams: #exam_one}, #{exam_two}, {exam_three}"enddefaverage_grade(exam_one,exam_two,exam_three)average==(exam_one+exam_two+exam_three)/3)endaverage=avrage_grade(exam_one,exam_two,exam_three).to_idefletter_grade(average-grade)ifaverage_grade<59puts"Grade: F"elseifaverage_grade>=60&&average_grade<=69puts"Grade: D"elsifaverage_grade>70&average_grade<=79puts'Grade: C"
elseif average_grade >= 80 && average_grade <= 89
puts "Grade: B"
elsif average_grade >= 90
puts "Grade: A'enddefpass_fail(average)ifaverage<59puts"Student is failing.
else puts "Studentispassing."
end
end
list_grade(exam_one, exam_two, exam_three)
puts "Average": #{average}"lettergrade(average)pass_fail(average)
Fixed:
# Calculating Grades (ok, let me think about this one)# Write a program that will average 3 numeric exam grades, return an average test score, a corresponding letter grade, and a message stating whether the student is passing.# Average Grade# 90+ A# 80-89 B# 70-79 C# 60-69 D# 0-59 F# Exams: 89, 90, 90# Average: 90# Grade: A# Student is passing.# Exams: 50, 51, 0# Average: 33# Grade: F# Student if failsputs"Input exam grade one:"exam_one=gets.chomp().to_iputs"Input exam grade two:"exam_two=gets.chomp().to_iputs"Input exam grade three:"exam_three=gets.chomp().to_ideflist_grade(exam_one,exam_two,exam_three)puts"Exams: #{exam_one}, #{exam_two}, #{exam_three}"enddefaverage_grade(exam_one,exam_two,exam_three)average=((exam_one+exam_two+exam_three)/3)endaverage=average_grade(exam_one,exam_two,exam_three).to_idefletter_grade(average_grade)ifaverage_grade<59puts"Grade: F"elsifaverage_grade>=60&&average_grade<=69puts"Grade: D"elsifaverage_grade>70&&average_grade<=79puts'Grade: C'elsifaverage_grade>=80&&average_grade<=89puts"Grade: B"elseaverage_grade==90puts"Grade: A"endenddefpass_fail(average)ifaverage<59puts"Student is failing"elseputs"Student is passing."endendlist_grade(exam_one,exam_two,exam_three)puts"Average: #{average}"letter_grade(average)pass_fail(average)
moduleEx2# This function will break up words for us.defEx25.brak_words(stuffwords=stuff.split(' ')returnwordend# Sorts the words.defEx25.sortwords(words)returnwords.sortend# Prints the first word after popping it off.dfEx25.print_first_word(words)word=words.pop(1)putsworend# Prints the last word after popping it off.defEx25:print_last_word(words)word=words.popputwordend# Takes in a full sentence and returns the sorted words.defEx25.sort_sentence(sentence)words=Ex25.break_words(sentence)returnEx25.sort_words(words)ed# Prints the first and last words of the sentence.defEx25.print_first_and_last(sentencewords=Ex25.break_words(sentenc)Ex25.print_first_wrd(word)Ex25.print_last_word(words)end# Sorts the words then prints the first and last one.defEx25.print_first_and_last_sorted(sentence)words=Ex25.sort_sentence(sentence)Ex25.print_fist_word(words)Ex25.print_last_word(words)endputs"Let's practice everything."puts'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.'poem=<<END\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
ENDED
puts "--------------"
puts poem
puts "--------------"
five = 10 - 2 3 - 6
puts "This should be five: #{five"
def secret_formula(started)
jelly_bens = started * 500
jars = jelly_beans / 1000
crate = jars / 100
return jelly_beans, jars, crates
end
start_point = 10000
beans, jars crates = secret_formula(start_point)
puts "Withastartingpointof: #{start_point}"puts"We'd have #{beansbeans,#{jars} jars, and #{crates} crates."start_point=start_point/10sentence="All good things come to those who wait."words=Ex25.break_words(sentence)sorted_words=Ex25.sort_words(words)Ex25.print_first_word(wrds)Ex25.print_last_wordwords)Ex25.print_first_word(sort_words)Ex25.print_last_word(sorted_words)sorted_words=Ex25.sort_sentenc(sentence)Ex25.print_first_and_last(sentence)Ex25:print_first_and_last_sorted(sentence)
Fixed:
# Just one solution - let us know if you have other fixes.# Note - we haven't actually learned several of the methods# and syntactical tricks in this exercise. Google them!moduleEx25# This function will break up words for us.defEx25.break_words(stuff)words=stuff.split(' ')returnwordsend# Sorts the words.defEx25.sortwords(words)returnwords.sortend# Prints the first word after popping it off.defEx25.print_first_word(words)word=words.pop(1)putswordend# Prints the last word after popping it off.defEx25.print_last_word(words)word=words.popputswordend# Takes in a full sentence and returns the sorted words.defEx25.sort_sentence(sentence)words=Ex25.break_words(sentence)returnEx25.sortwords(words)end# Prints the first and last words of the sentence.defEx25.print_first_and_last(sentence)words=Ex25.break_words(sentence)Ex25.print_first_word(words)Ex25.print_last_word(words)end# Sorts the words then prints the first and last one.defEx25.print_first_and_last_sorted(sentence)words=Ex25.sort_sentence(sentence)Ex25.print_first_word(words)Ex25.print_last_word(words)endendputs"Let's practice everything."puts"You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs."poem="<<STARTED
\tThe lovely world
\twith logic so firmly planted
\tcannot discern
\tthe needs of love
\tnor comprehend passion from intuitio
\tand requires an explanation
\twhere there is none.
ENDED>>"puts"--------------"putspoemputs"--------------"five=5puts"This should be five: #{five}"defsecret_formula(started)jelly_beans=started*500jars=jelly_beans/1000crates=jars/100returnjelly_beans,jars,cratesendstart_point=10000beans,jars,crates=secret_formula(start_point)puts"With a starting point of: #{start_point}"puts"We'd have #{beans} beans, #{jars} jars, and #{crates} crates."start_point=start_point/10sentence="All good things come to those who wait."words=Ex25.break_words(sentence)sorted_words=Ex25.sortwords(words)Ex25.print_first_word(words)Ex25.print_last_word(words)Ex25.print_first_word(sorted_words)Ex25.print_last_word(sorted_words)sorted_words=Ex25.sort_sentence(sentence)Ex25.print_first_and_last(sentence)Ex25.print_first_and_last_sorted(sentence)