4thSpace 4thSpace - 3 months ago 20
Ruby Question

How to do numeric comparison in Ruby?

Why does the following output the else part?

some_value = 100

case some_value
when some_value <= 200
puts "less than 200"
else
puts "not less than 200"
end

Answer

The case...when...end construct uses === to check for a match.

Your code evaluates as:

case 100
when some_value <= 200 # when (some_value <= 200) === 100, which is (true === 100), which doesn't match
  puts "less than 200"
else
  puts "not less than 200"
end

You can omit the value after case to make the construct behave like an if...else....

some_value = 100

case
when some_value <= 200
  puts "less than 200"
else
  puts "not less than 200"
end
Comments