Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ruby support ranges in case statement?

Tags:

ruby

I want to do this:

case cost

    when cost between 1 and 3 then cost * 1.1
    when cost between 3 and 5 then cost * 1.2
else
    0
like image 203
Blankman Avatar asked Nov 09 '10 03:11

Blankman


People also ask

Can you use || IN CASE statement Ruby?

If you are eager to know how to use an OR condition in a Ruby switch case: So, in a case statement, a , is the equivalent of || in an if statement.

How do you create a range in Ruby?

Ranges as Sequences Sequences have a start point, an end point, and a way to produce successive values in the sequence. Ruby creates these sequences using the ''..'' and ''...'' range operators. The two-dot form creates an inclusive range, while the three-dot form creates a range that excludes the specified high value.

What is a case statement in Ruby?

The case statement is a multiway branch statement just like a switch statement in other languages. It provides an easy way to forward execution to different parts of code based on the value of the expression.

Does Ruby case fall through?

No, Ruby's case statement does not fall through like Java.


2 Answers

Yes, since Range#=== is defined to be the same as include?, you can use ranges in case statements:

case cost
when 1..3 then cost * 1.1
when 3..5 then cost * 1.2
like image 66
sepp2k Avatar answered Sep 29 '22 15:09

sepp2k


Yes. I don't know why you didn't think to Google this or just try it (which is the beauty of Ruby, IMO: things usually work the way you think they should), but I'll answer just the same: http://ilikestuffblog.com/2008/04/15/how-to-write-case-switch-statements-in-ruby/

Specifically:

case expression
when min..max
   statements
else
   statements
end
like image 40
Mike Linington Avatar answered Sep 29 '22 13:09

Mike Linington