Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save carolineartz/0381844e2cf8bc2f54de to your computer and use it in GitHub Desktop.
Save carolineartz/0381844e2cf8bc2f54de to your computer and use it in GitHub Desktop.
Exercise: Calculate the letter grade of a series of grades Create a method get_grade that accepts an Array of test scores. Each score in the array should be between 0 and 100, where 100 is the max score. Compute the average score and return the letter grade as a String, i.e., 'A', 'B', 'C', 'D', 'E', or 'F'.
# PSEUDOCODE
# INPUT: array of grades
# OUPUT: a string representation of the letter grade that corresponds with
# the average score of the array of grades
# STEPS: Compute the average value of the values in teh input array
# divide the average by the length of input array => computes average score
# define letter grade distribution
# convert the average score to its corresponding letter grade
# return letter grade, as string
# INITIAL CODE:
def get_grade(scores)
total = 0
scores.each do | el |
total += el.to_f
end
avg = total / scores.length
case avg
when 0..59 then "F"
when 60..69 then "D"
when 70..79 then "C"
when 80..89 then "B"
when 90..100 then "A"
end
end
# REFACTORED CODE:
def get_grade(scores)
avg = scores.reduce(:+).to_f / scores.length
case avg
when 0..59 then "F"
when 60..69 then "D"
when 70..79 then "C"
when 80..89 then "B"
when 90..100 then "A"
end
end
# REVIEW/REFLECT I was successful when solving this problem pretty early.
# However, I did have some trouble with Socrates acceping my oroginal
# solution, despite it running without problem elsewhere. The good thing about
# that was that it forced me to really disect and become familiar with this
# problem while attempting to find what might be the culprate. My initial
# thought was related to type conversion as removing the `avg = 0" I
# originally defined directly below total = 0 resolved whatever was triggering
# the error in Socrates.
# I thought to use the case statement off the bat-most likely thanks to my
# little bit of experience with Java. I was a big fan of the Java's switch
# statement. I had to look up the syntax because I rememebred it was
# different. I was glad to use it again and become familiar with Ruby's
# implementation.
# When refactoring, I aimed to trim down and combine the the part of the method
# before the case statement. Since we just totaled an array of numbers, I used
# that knowledge to accomplish the task in (what I think is?) pretty concise
# but sufficiently clear code. It's still hard for me to...remember?
# understand?...the `:+` notation both here and following an ampersand. Maybe
# I'll reach out to Jonathan about it.
# This problem was really good for reminding me of Ruby's case syntax and
# drilling home ways to sum an array.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment