两个相似的脚本在这里表现出非常奇怪的行为。
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) 另一个是将 1
放入控制台日志。
score = 0
ammount = 4
score += case ammount
when ammount >= 3; 10
else 1
end
puts score
我希望这两个脚本都能将 10
输出到控制台。我错了吗?为什么?
最佳答案
当给定一个参数时,case 语句检查对象是否相等(与调用 ===
相同),这可以用于单个值或超过范围。在你的情况下,你并没有真正检查平等,但它可以这样写:
score += case
when amount >= 3 then 10
when amount < 3 then 1
end
但是,这对于您要尝试执行的操作(一个非此即彼的条件)来说非常冗长。使用普通的 if...else
或三元语句会更简单:
score += amount >= 3 ? 10 : 1
关于ruby - 具有真值的案例陈述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13317310/