In other languages also know an switch statement, ruby uses case to match a value
against conditions:
Unlike other languages ruby has some neat features that allow you to test against
ranges, multiple values or classes as well:
You can even use it without passing a value. I think this is extremely ugly but
decide for yourself:
Well, no. Don’t decide for yourself. It is ugly. And useless given that we have if/else
Case equality
So how does this work? How does ruby know when to match? Enter the case equality operator:
===
Everything that responds to === can be used in the when clause:
Sugar
As you might know writing
foo === bar
is just syntactic sugar for
foo.===(bar)
What Ruby does is to call the === method on the object you passed to when, supplying the value you passed to case as the single argument.
Procs and Lambdas
In 1.9 === was added to Proc as a way to invoke it. This allows it to be the target of a when clause in case statement:
Strange world
When you use a Proc but do not supply a value to case then strangely ruby just evaluates the first when clause:
I’d have expected an exception.
But you came to the conclusion that a case statement without a value is ugly anyway, right?
Performance
What about performance of a case statement compared to if/else?
Well, if you don’t use Procs then the performance is the same. But since calling Procs
is expensive it might be worth rewriting a case to if/else:
Running above benchmark should show you something like:
Of course the runtime of the code depends on the value of thing. Adjust it so that first, second or third case is matched to see the differences.
But in any case: using Procs is slower than the corresponding if/else.