Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a case/when checking a negative number

Tags:

ruby

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?

like image 500
MrPizzaFace Avatar asked Dec 19 '22 19:12

MrPizzaFace


2 Answers

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
like image 27
tckmn Avatar answered Jan 01 '23 18:01

tckmn


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
like image 98
Ash Wilson Avatar answered Jan 01 '23 16:01

Ash Wilson