DonTerry DonTerry - 1 year ago 69
Ruby Question

What are the various ways of doing this code?

Create a function that takes a number as an argument and returns a grade based on that number.

Score Grade

Anything greater than 1 or less than 0.6 'F'

0.9 or greater "A"

0.8 or greater "B"

0.7 or greater "C"

0.6 or greater "D"

I was trying to figure out another way to write this code because the interpreter won't accept it. Can someone assist me with this?

def grader(score)
if score >= 0.9
return "A"
elsif score >= 0.8
return "B"
elsif score >= 0.7
return "C"
elsif score >= 0.6
return "D"
elsif score < 0.5 or score > 1.01
return "F"
return "O"

Answer Source

I'll suggest to use case statement for that purpose:

def grader(score)
  case score
  when 0.9..1    then 'A'
  when 0.8...0.9 then 'B'
  when 0.7...0.8 then 'C'
  when 0.6...0.7 then 'D'
  else                'F'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download