Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Is there a right way to indent a case statement? [closed]

A number of blogs and tutorial have different indentations when they implement a case statement. Each have different indentation in reference to the 'when' lines. Is there a best practice for indenting when using a case loop?

like image 260
andy4thehuynh Avatar asked Jul 17 '13 18:07

andy4thehuynh


People also ask

What is a case statement in Ruby?

Case statement in the Ruby is a way to execute different codes and expressions on the basis of the values provided to the case, case statement in Ruby is similar to basic switch cases in the other programming languages.

What is the use of switch case in Ruby?

Case statement in the Ruby is a way to execute different codes and expressions on the basis of the values provided to the case, case statement in Ruby is similar to basic switch cases in the other programming languages. In case of the switch case in Ruby it has three main components case (it is similar to switch in general concept, it takes the ...

What is a switch statement in Ruby?

Note: In other programming languages this is known as a switch statement. The components of a case statement in Ruby: Starts a case statement definition. Takes the variable you are going to work with. Every condition that can be matched is one when statement. If nothing matches then do this.

Why is the condition reversed in Ruby on the left?

As you can see, the condition is reversed because Ruby calls === on the object on the left. The === is just a method that can be implemented by any class. In this case, Range implements this method by returning true only if the value is found inside the range.


2 Answers

The consensus is to indent when as the same level as case.

case sym
when :foo then ...
when :bar then ...
else ...
end

I think this is well established, and have not seen any authentic source that claims otherwise.

like image 196
sawa Avatar answered Oct 23 '22 20:10

sawa


This is the way I've seen it used. The 'what happens in the event of the 'when' should be on the next line and indented.

case something
when 'a'
  what happens when 'a'
when 'b'
  what happens when 'b'
when 'c'
  what happens when 'c'
end
like image 20
Schechter Avatar answered Oct 23 '22 20:10

Schechter