Chris Clouten
Chris Clouten

Reputation: 1085

Ruby case/when vs if/elsif

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?

Upvotes: 9

Views: 12259

Answers (2)

Chuck
Chuck

Reputation: 237070

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?"

Upvotes: 9

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

Ruby's begin/rescue/end is more similar to Python's try/catch (assuming Python's try/catch is similar to Javascript, Java, etc.). In both of the above the code runs, catches errors and continues.

case/when is like C's switch and ignoring the === operator that bjhaid mentions operates very much like if/elseif/end. Which you use is up to you, but there are some advantages to using case when the number of conditionals gets long. No one likes /if/elsif/elsif/elsif/elsif/elsif/end :-)

Ruby has some other magical things involving that === operator that can make case nice, but I'll leave that to the documentation which explains it better than I can.

Upvotes: 3

Related Questions