重构如果elsif在Ruby中

时间:2015-06-02 21:07:16

标签: ruby if-statement

有没有办法重构此代码并使其更清晰?你能用更少的布尔来解决这个问题吗?

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 

2 个答案:

答案 0 :(得分:8)

如何使用Rangecase声明?

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

答案 1 :(得分:3)

对于大型课程,效率至关重要:

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"