Ruby if, else and unless statement
if, else and unless
Ruby has a variety of ways to control execution that is pretty common to other modern languages. All the expressions described here return a value.
Here, we have explained if Expression, Ternary if, unless Expression, Modifier if and unless and case Expression
For the tests in these control expressions :
- nil and false are false-values
- true and any other object are true-values
Ruby: if Expression
The if expressions execute a single statement or a group of statements if a certain condition is met. It can not do anything if the condition is false. For this purpose else is used.
Syntax:
if conditional [then] code... [elsif conditional [then] code...]... [else code...] end
The simplest if expression has following two parts :
- a "test" expression
- a “then” expression.
If the "test" expression evaluates to a true then the "then" expression is evaluated.
Example:
Output:
H:\>ruby abc.rb x is greater than 8
The then is optional:
Output:
H:\>ruby abc.rb x is greater than 8
You can also add an else expression. If the test does not evaluate to true, then the else expression will be executed :
Example:
Output:
H:\>ruby abc.rb x is not greater than 18
You can add an arbitrary number of extra tests to an if expression using elsif. An elsif executes when all tests above the elsif are false.
Example:
Output:
H:\>ruby abc.rb x is Hundred.
Ruby: Ternary if
You may also write a if-then-else expression using ? and :
Is the same as this if expression :
Ruby: unless Statement:
The unless expression is the opposite of the if expression. If the value is false the "then" expression is executed :
Syntax:
unless conditional [then] code [else code ] end
Example:
The following code prints nothing as the value of x is 1.
The following code will print "x is greater than 0".
Example:
Ruby: Modifier if and unless
You can use if and unless to modify an expression. When used as a modifier the left-hand side is the "then" expression and the right-hand side is the "test" expression:
Following code will print 1.
The above code will print 0.
Previous:
Ruby Dot And Double Colon Operators
Next:
Ruby Case Statement