You are mixing two different types of case statements:
case var
when 1
dosomething
when 2..3
doSomethingElse
end
case
when var == 1
doSomething
when var < 12
doSomethingElse
end
case myvar
when proc { |n| n < -5 }
do somethingA
when -5..-3
do special_something_XX
when -2..-1
do special_something_YY
when proc { |n| n == 0 }
do somethingB
when proc { |n| n > 0 }
go somethingC
end
end
I am not personally convinced that you wouldn't be better off with if statements, but if you want a solution in that form:
Inf = 1.0/0
case myvar
when -Inf..-5
do somethingA
when -5..-3
do special_something_XX
when -2..-1
do special_something_YY
when 0
do somethingB
when 0..Inf
do somethingC
end
My preferred solution follows. Here the order matters and you have to repeat the myvar, but it's much harder to leave out cases, you don't have to repeat each bound twice, and the strictness (< vs <= rather than .. vs ...) is much more obvious.
if myvar <= -5
# less than -5
elsif myvar <= -3
# between -5 and -3
elsif myvar <= -1
# between -3 and -1
elsif myvar <= 0
# between -1 and 0
else
# larger than 0
end
def project_completion(percent)
case percent
when percent..25
"danger"
when percent..50
"warning"
when percent..75
"info"
when percent..100
"success"
else
"info"
end
end
Using infinity may help
case var
when -Float::INFINITY..-1
when 0
when 1..2
when 3..Float::INFINITY
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