Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby case/when vs if/elsif

Tags:

ruby

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?

like image 421
Chris Clouten Avatar asked Feb 13 '14 17:02

Chris Clouten


People also ask

Are case statements better than if statements?

The first of which is that in most cases, case statements are slightly more efficient than a whole bunch of if statements.

Does Ruby case fall through?

The case statement in Ruby, on the other hand, can be seen as a shorthand for a series of if statements. There is no fallthrough, only the first matching case will be executed.

Does Ruby have else if?

Notice Ruby uses elsif, not else if nor elif. Executes code if the conditional is true. If the conditional is not true, code specified in the else clause is executed.


2 Answers

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

like image 179
Chuck Avatar answered Dec 04 '22 08:12

Chuck


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.

like image 39
Philip Hallstrom Avatar answered Dec 04 '22 07:12

Philip Hallstrom