if..elsif..end / unless..end

Ruby features the standard if conditional in both expression and expression modifier form. unless condition is exactly equivalent to if not condition in all contexts.

An if/unless expression returns the value of its last expression.

Block form

Syntax

 if condition [then]
   code
 [elsif condition [then]
   code]
 [else

   code]
 end
 unless condition
   code
 [else

   code]
 end

Explanation

The basic expression form of if looks like this, and must end with an end:

 if some_condition_expression

   # This section executed if some_condition_expression is true
 end

The else-keyword can be used to provide a section that will be executed if the condition expression evaluates to false. Only one else may appear in an if-expression:

 if some_condition_expression
   # This section executed if some_condition_expression is true
 else

   # This section executed if some_condition_expression is false
 end

The elsif-keyword can be used to create multiple mutually exclusive conditionals. If the conditional in the initial if is not true, then each elsif conditional is evaluated in descending order until one is true. If none is, the else-section is executed if there is one:

 if cond_one

   # cond_one is true
 elsif cond_two
   # cond_one is not true and cond_two is true
 elsif cond_three
   # cond_one is not true and cond_two is not true and cond_three is true
 else
   # cond_one, cond_two and cond_three are all not true
 end

With unless, it is not possible to define elsifs, just else.

There if expression may have an optional then added, but it is usually elided.

 if some_condition_expression then
   # ...
 elsif some_other_condition_expression then

   # ...
 end

However, then is necessary if you want to keep the if expression in a single line.

 if some_condition_expression then do_something end