Two similar scripts are showing very strange behaviours here.
A) The code below is throwing a nil can't be coerced into Fixnum (TypeError):
score = 0
ammount = 4
score += case ammount
when ammount >= 3; 10
when ammount < 3; 1
end
puts score
B) And this other one is putting 1 into the console log.
score = 0
ammount = 4
score += case ammount
when ammount >= 3; 10
else 1
end
puts score
I would expect both scripts to output 10 onto the console. Am I wrong? Why?
When given an argument, the case statement checks for object equality (same as calling
===), which can be used with single values or over ranges. In your case, you’re not really checking for equality, but it can be written like this:However, this is pretty verbose for what you’re trying to do (an either/or condition). It’s simpler to use a plain
if...elseor a ternary statement: