Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby case statement with comparison [duplicate]

Tags:

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
like image 587
user101289 Avatar asked Mar 27 '14 22:03

user101289


1 Answers

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.

like image 69
Arup Rakshit Avatar answered Oct 19 '22 20:10

Arup Rakshit