Ruby case/when vs if/elsif
ruby
Solution
The `case` expression is not at all like a try/catch block. The Ruby equivalents to `try` and `catch` are `begin` and `rescue`.
In general, the case expression is used when you want to test one value for several conditions. For example:
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
The case expression is orthogonal to the switch statement that exists in many other languages (e.g. C, Java, JavaScript), though Python doesn't include any such thing. The main difference with case is that it is an expression rather than a statement (so it yields a value) and it uses the `===` operator for equality, which allows us to express interesting things like "Is this value a String? Is it 0? Is it in the range 1..5?"
Problem
The `case`/`when` statements remind me of `try`/`catch` statements in Python, which are fairly expensive operations. Is this similar with the Ruby `case`/`when` statements? What advantages do they have, other than perhaps being more concise, to `if`/`elsif` Ruby statements? When would I use one over the other?