Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate letter grade using a series of grades

Noob to Ruby here. Working through some exercises and have hit a wall.

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

I keep returning the error:

avg.rb:1: syntax error, unexpected tLBRACK, expecting ')'
def get_grade([100,90,80])
               ^
avg.rb:1: syntax error, unexpected ')', expecting $end

Here's what I have so far. I'd like to stick with the methods below or .join as I'm trying to work with the methods we're learning in class. So sum, inject, etc won't necessarily be helpful. And I apologize in advance for the specificity of the request :) I'm sure there's a way better way that is way less code, but I'm just trying to learn it this way to start.

    def get_grade([100,90,80])
      get_grade = (array[0] + array[1] + array[2]).to_i / array.length.to_i
    case get_grade
      when 90..100
      "A"
      when 80..90
       "B"
      when 70..80
       "C"
      when 60..70
       "D"
      when 0..60
       "F"
      else
     "Error"
      end
    end

    puts get_grade([100,90,80])
like image 471
ideahed Avatar asked May 20 '13 01:05

ideahed


2 Answers

You can't just randomly dump an array literal like [100,90,80] into the parameter list of a function definition. Judging by the function body, I think you meant to accept a single parameter array:

def get_grade(array)
  grade = (array[0].to_i + array[1].to_i + array[2].to_i) / array.length
  case grade
    # unchanged
  end
end
like image 120
michaelb958--GoFundMonica Avatar answered Nov 13 '22 02:11

michaelb958--GoFundMonica


A terse replacement of the big case statement, for fun:

def letter_grade( score ) # assumes that score is between 0 and 100 (not 0-1)
  %w[F F F F F F D C B A][ (score/10.0).floor ] || 'A' # handles grades >=100
end

Or, for more granularity:

def letter_grade( score ) # score is between 0 and 100 (not 0-1)
  grades = %w[F F F F F F F F F F F F F F F F F F D- D D+ C- C C+ B- B B+ A- A A+ A+]
  grades[ (3.0*score/10).floor ]
end
like image 31
Phrogz Avatar answered Nov 13 '22 02:11

Phrogz