5
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?

Wayne Conrad
  • 103,207
  • 26
  • 155
  • 191
MrPizzaFace
  • 7,807
  • 15
  • 79
  • 123

2 Answers2

7

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
Ash Wilson
  • 22,820
  • 3
  • 34
  • 45
  • Great explanation. Can you give me a better understanding of `-Float::Infinity..0` or perhaps a link? Thanks. – MrPizzaFace Jan 07 '14 at 22:06
  • Well, since you want that `when` to execute for any negative number, the range of all negative numbers is `-Infinity` to `0`, or `-Float::INFINITY..0` (and, like Doorknob of Snow said below, `Float::INFINITY` was introduced in 1.9.2). http://stackoverflow.com/questions/5778295/how-to-express-infinity-in-ruby – Ash Wilson Jan 07 '14 at 23:02
  • should be `...`, not `..`, otherwise you catch `0` – akostadinov Dec 15 '22 at 22:29
4

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
tckmn
  • 57,719
  • 27
  • 114
  • 156