ruby案例陈述与比较

时间:2014-03-27 22:04:42

标签: ruby case

有没有办法在ruby中使用带有整数比较的case语句?我找到了很多比较字符串的示例,但下面的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 个答案:

答案 0 :(得分:15)

case..when区块中,您无法执行===以外的任何比较。所以我写下你的代码如下:

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 隐式,因此无需提及。

答案 1 :(得分:0)

像这样改写你的案子:

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