Javascript 你能用Case语句在Ruby中无限计数吗?
我试图计算如果总分超过100分会发生什么。我目前正在使用case语句来输出不同的分数。将是表示100以上范围的最佳解决方案,允许我们输出“A++”Javascript 你能用Case语句在Ruby中无限计数吗?,javascript,ruby-on-rails,ruby,rubygems,Javascript,Ruby On Rails,Ruby,Rubygems,我试图计算如果总分超过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.
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
子句的典型情况。假设每个score参数都是非负的,为什么不将您的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]
您可以为案例提供一个proc,以允许您使用类似
>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
下面是一个使用无穷大的漂亮解决方案: 首先提到
我想得很清楚;我只是不知道是否有其他方法可以使用无穷大或其他方法来实现这一点?谢谢可以,但是Ruby没有定义像
Fixnum::MAX
这样的常量。计算出实际的价值会有点太复杂,比如或。因此,最好还是坚持一个简单的解决方案。@NicNilov用户传递一个或多个负数作为参数(使总数<0)怎么样?这是lambda的一个很好的用法,但它有点重复了case
语句的语义。我更喜欢@Nic的解决方案,但是您可以在case语句中添加以下任一行:when 101..Float::INFINITY然后是'A++'
或者when 101..total然后是'A++'
。
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