number = -5
case number
when number < 0
return "Please enter a number greater than 0."
when 0..1
return false
when 2
return true
end
...
I expected it to return "Please enter a number greater than 0", but instead it returned nil. Why is that? How can I check if the number is less than 0?
when number < 0 will be the same as when true in this case, because number is indeed less than zero, and the when will not be entered since -5 != true.
You could try
when (-1.0/0)..0 # negative Infinity to 0
Or, if you're using 1.9.2 or above:
when -Float::INFINITY..0
When you give a variable to case, it's compared against each when clause with the === method. The first === to return true will be the branch that's executed.
In your case, number < 0 is evaluating to true, and -5 === true is false!
What you want to do is either leave the number off of the case, and make all of the when clauses boolean:
case
when number < 0
return "Please enter a number greater than 0."
when number.between?(0, 1)
return false
when number == 2
return true
end
Or leave the number on, but make all of the whens values that you can compare against:
case number
when -Float::INFINITY..0 # or (-1.0/0)..0
return "Please enter a number greater than 0."
when 0..1
return false
when 2
return true
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