您可以使用 Case 语句在 Ruby 中无限计数吗?

Can You Count Infinitely in Ruby Using a Case Statement?

我正在尝试计算如果总分平均超过 100 分会发生什么情况。我目前正在使用 case 语句输出不同的分数。将是表示 100 以上范围的最佳解决方案,使我们能够输出 'A+++'.

def get_grade(score_1, score_2, score_3)
  total = (score_1 + score_2 + score_3)/3

  case total
  # What if the score is above 100? 
  # I want it to express 'A+++'
  when 90..100 then 'A'
  when 80..89 then 'B'
  when 70..79 then 'C'
  when 60..69 then 'D'
  else             'F'
  end
end

p get_grade(91, 97, 93) # => 'A'
p get_grade(52, 57, 51) # => 'D'
p get_grade(105, 106, 107) # => 'A++'

这将是 else 子句的典型情况。为什么不修改你的 case 声明看起来像这样,假设每个分数参数都是非负的:

case total
  when 90..100 then 'A'
  when 80..89 then 'B'
  when 70..79 then 'C'
  when 60..69 then 'D'
  when 0..59 then 'F'
  else 'A+++'
end

您可以组合方法并使用比较

...
else
    if total > 100
        "A+++"
    else
         "F"
    end
end

如果想玩一点,可以把case语句改成:

(total > 100) ? "A+++" : "FFFFFFDCBAA"[(total/10).to_i]

您可以为案例提供过程以允许您使用像 > 100

这样的表达式
def get_grade(score_1, score_2, score_3)
  total = (score_1 + score_2 + score_3)/3

  case total
  # What if the score is above 100? 
  # I want it to express 'A+++'
  when 90..100 then 'A'
  when 80..89 then 'B'
  when 70..79 then 'C'
  when 60..69 then 'D'
  when ->(n) { n > 100 } then 'A+++'
  else 'F'
  end
end

这是一个使用无穷大的绝妙解决方案:

首先被

提及
case total
  when 101..Float::INFINITY then 'A+++'
  when 90..100 then 'A'
  when 80..89 then 'B'
  when 70..79 then 'C'
  when 60..69 then 'D'
  else 'F'
end