ruby 练习:计算一系列成绩的字母等级创建一个接受一系列考试成绩的方法get_grade。每个得分都在

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 练习:计算一系列成绩的字母等级创建一个接受一系列考试成绩的方法get_grade。每个得分都在相关的知识,希望对你有一定的参考价值。

# 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.

以上是关于ruby 练习:计算一系列成绩的字母等级创建一个接受一系列考试成绩的方法get_grade。每个得分都在的主要内容,如果未能解决你的问题,请参考以下文章

y轴上的jquery highcharts文本

switch 练习

分段故障核心转储...?

实验四:分支结构

查询英语分数在 80-90之间的同学?

scratch计算成绩总和 电子学会图形化编程scratch等级考试三级真题和答案解析2021-6