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
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.
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.
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.
No, Ruby's case statement does not fall through like Java.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With