Reputation: 75
Is there a way to refactor this code and make it cleaner? Can you use fewer booleans to solve this problem?
def get_grade(grade_num)
if grade_num > 100
return "Please enter a number between 0 and 100"
elsif grade_num <=100 && grade_num >= 90
return 'A'
elsif grade_num < 90 && grade_num >= 80
return 'B'
elsif grade_num < 80 && grade_num >= 70
return 'C'
elsif grade_num < 70 && grade_num >= 60
return 'D'
elsif grade_num < 60
return 'F'
end
end
Upvotes: 1
Views: 889
Reputation: 107142
What about using Range
and a case
statement?
def get_grade(grade)
case grade
when 90..100 then 'A'
when 80...90 then 'B'
when 70...80 then 'C'
when 60...70 then 'D'
when 0...60 then 'F'
else
'Please enter a number between 0 and 100'
end
end
Upvotes: 8
Reputation: 110755
For large classes, where efficiency is paramount:
GRADES = {
( 0...60) => "Fail",
(60...70) => "D",
(70...80) => "C",
(80...90) => "B",
(90..100) => "A" }
TO_MARK = GRADES.flat_map { |r,mark| r.to_a.product([mark]) }.to_h
#=> {0=>"Fail", 1=>"Fail",..., 59=>"Fail", 60=>"D",..., 69=>"D",
# 70=>"C",..., 79=>"C", 80=>"B",..., 89=>"B", 90=>"A",..., 100=>"A"}
TO_MARK[33] #=> "Fail"
TO_MARK[65] #=> "D"
TO_MARK[80] #=> "B"
TO_MARK[90] #=> "A"
Upvotes: 3