AbUndZu AbUndZu - 2 months ago 6
Ruby Question

what types of instructions can i put under (case) when statements?

What types of instructions can I put under when? Some of my code works under if/else, but does not work under case when.

For example

def categories(massIndex)
case massIndex
when >= 30.0
"obese"
[some instructions like this]
else
"error"
end


I always see error like this:

bmi.rb:8: syntax error, unexpected >=
when >= 30.0


But when i do it with if/else, it works:

def categories(massIndex)
if massIndex >= 25
"something"
else
"error"
end
end


Can I fix it still using case, or must I use the if/else?

Answer
case x
when y
  puts "y"
when z
  puts "z"
end

is equivalent to

if y === x
  puts "y"
elsif z === x
  puts "z"
end

For example

case "hello"
when Array
  puts "Array"
when String
  puts "String"
end
  #=> "String"

x = "hello"
if Array === x
  puts "Array"
elsif String === x
  puts "String"
end
  #=> "String"

See String#===.

So when you write

case massIndex
when >= 30.0
  "obese"
...

Ruby attempts to evaluate

>= 30.0 === massIndex

causing her to raise a syntax error.