你可以使用案例陈述在Ruby中无限地计算吗?

时间:2016-07-28 20:55:30

标签: javascript ruby-on-rails ruby rubygems

我正在尝试计算如果总得分平均超过100会发生什么。我目前正在使用案例陈述来输出不同的分数。将表达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++'

4 个答案:

答案 0 :(得分:4)

这将是var ids = {"1": "one", "2": two} .state('module',{ url: '/module/:id', controller: 'moduleoneCtrl', templateUrl: function($stateParams){ return path + 'views/'+ ids[$stateParams.id] +'.html'; } }); 子句的典型案例。为什么不将您的else语句重写为:

case

答案 1 :(得分:3)

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

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

如果你想玩一点,你可以将case语句改为:

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

答案 2 :(得分:2)

您可以为案例提供过程,以允许您使用类似于>的表达式。 100 def get_grade(score_1,score_2,score_3)   总计=(score_1 + score_2 + score_3)/ 3   案件总数   #如果分数高于100怎么办?   #我希望它表达“A +++'   当90..100然后' A'   当80..89然后' B'   当70..79然后' C'   当60..69然后' D'   当 - >(n){n> 100}然后' A +++'   别的' F'   结束 结束

答案 3 :(得分:0)

这是一个使用无穷大的漂亮解决方案:

首先由@CarySwoveland

提及
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