红宝石案例陈述与比较 [英] ruby case statement with comparison
本文介绍了红宝石案例陈述与比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种方法可以将case
语句与ruby中的整数比较一起使用?我发现了很多比较字符串的示例,但是下面的case
示例由于语法错误而失败.
Is there a way to use a case
statement with integer comparisons in ruby? I have found lots of examples comparing strings, but my case
example below fails with syntax errors.
def get_price_rank(price)
case price
when <= 40
return 'Cheap!'
when 41..50
return 'Sorta cheap'
when 50..60
return 'Reasonable'
when 60..70
return 'Not cheap'
when 70..80
return 'Spendy'
when 80..90
return 'Expensive!'
when >= 90
return 'Rich!'
end
end
推荐答案
在case..when
块中,除===
之外,您无法执行任何比较.因此,我将按照以下方式编写您的代码:
In case..when
block you can't perform any comparisons except ===
. So I'd write your code as below :
def get_price_rank(price)
case price
when 41..50
'Sorta cheap'
when 50..60
'Reasonable'
when 60..70
'Not cheap'
when 70..80
'Spendy'
when 80..90
'Expensive!'
else
if price >= 90
'Rich!'
elsif price <= 40
'Cheap!'
end
end
end
return
是隐式,因此无需提及.
这篇关于红宝石案例陈述与比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文