case
/when
语句让我想起 Python 中的 try
/catch
语句,它们相当昂贵操作。这与 Ruby 的 case
/when
语句相似吗?除了可能更简洁之外,与 if
/elsif
Ruby 语句相比,它们有什么优势?我什么时候会用一个而不是另一个?
最佳答案
case
表达式一点也不像 try/catch block 。 try
和 catch
的 Ruby 等效项是 begin
和 rescue
。
一般情况下,当你想在多个条件下测试一个值时使用 case 表达式。例如:
case x
when String
"You passed a string but X is supposed to be a number. What were you thinking?"
when 0
"X is zero"
when 1..5
"X is between 1 and 5"
else
"X isn't a number we're interested in"
end
case 表达式与存在于许多其他语言(例如 C、Java、JavaScript)中的 switch 语句正交,尽管 Python 不包含任何此类内容。与 case 的主要区别在于它是一个表达式而不是语句(因此它产生一个值)并且它使用 ===
运算符来表示相等性,这使我们能够表达有趣的事情,例如“是这个值是一个字符串?它是 0 吗?它在 1..5 范围内吗?”
关于Ruby case/when 对比 if/elsif,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21761475/