ruby case statement with comparison [duplicate]

孤街浪徒 提交于 2019-12-21 17:02:38

问题


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

回答1:


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:


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


来源:https://stackoverflow.com/questions/22700194/ruby-case-statement-with-comparison

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!