This question already has an answer here:
这个问题在这里已有答案:
- Ruby range: operators in case statement 3 answers
- Ruby范围:运算符在case语句3中的答案
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.
有没有办法在ruby中使用带有整数比较的case语句?我找到了很多比较字符串的例子,但是下面我的案例示例因语法错误而失败。
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
2 个解决方案
#1
14
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
is implicit, thus no need to mention.
返回是隐含的,因此无需提及。
#2
0
Rewrite your case like this:
像这样改写你的情况:
case price
when 0..40 then
return 'Cheap!'
when 41..50 then
return 'Sorta cheap'
when 50..60 then
return 'Reasonable'
when 60..70 then
return 'Not cheap'
when 70..80 then
return 'Spendy'
when 80..90 then
return 'Expensive!'
else
return 'Rich!'
end
#1
14
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
is implicit, thus no need to mention.
返回是隐含的,因此无需提及。
#2
0
Rewrite your case like this:
像这样改写你的情况:
case price
when 0..40 then
return 'Cheap!'
when 41..50 then
return 'Sorta cheap'
when 50..60 then
return 'Reasonable'
when 60..70 then
return 'Not cheap'
when 70..80 then
return 'Spendy'
when 80..90 then
return 'Expensive!'
else
return 'Rich!'
end