Ruby Decision
# Ruby Conditional Statements
Ruby provides several common conditional structures. Here, we will explain all the conditional statements and modifiers available in Ruby.
## Ruby _if...else_ Statement
## Syntax
if conditionalcode... [elsif conditionalcode...]... [else code...]end
The _if_ expression is used for conditional execution. The values _false_ and _nil_ are considered false, and all other values are considered true. Please note that Ruby uses `elsif`, not `else if` or `elif`.
If _conditional_ is true, then _code_ is executed. If _conditional_ is not true, then the _code_ specified in the else clause is executed.
Usually, we omit the reserved word `then`. If you want to write a complete if statement on one line, you must separate the condition and the code block with `then`, as shown below:
if a == 4 then a = 7 end
## Example
#!/usr/bin/ruby# -*- coding: UTF-8 -*-x=1 if x>2 puts"x is greater than 2"elsif x2 puts"x is less than or equal to 2"else puts"x is greater than 2"end
[Try it Β»](#)
The output of the above example is:
x is less than or equal to 2
## Ruby _unless_ Modifier
## Syntax
code unless conditional
If _conditional_ is false, then _code_ is executed.
## Example
#!/usr/bin/ruby# -*- coding: UTF-8 -*-$var = 1 print"1 -- This line is printedn"if$var print"2 -- This line is not printedn"unless$var$var = false print"3 -- This line is printedn"unless$var
[Try it Β»](#)
The output of the above example is:
1 -- This line is printed3 -- This line is printed
## Ruby _case_ Statement
## Syntax
case expression[when expression[, expression ...]code]... end
The `case` statement first evaluates an _expression_, then matches the result against the branches.
It uses the **===** operator to compare the _expression_ specified in **when**. If they match, the content of the **when** block is executed.
Usually, we omit the reserved word `then`. If you want to write a complete when statement on one line, you must separate the condition and the code block with `then`, as shown below:
when a == 4 then a = 7 end
Therefore:
case expr0 when expr1, expr2 stmt1 when expr3, expr4 stmt2 else stmt3 end
is basically similar to:
_tmp = expr0 if expr1 === _tmp || expr2 === _tmp stmt1 elsif expr3 === _tmp || expr4 === _tmp stmt2 else stmt3 end
## Example
#!/usr/bin/ruby# -*- coding: UTF-8 -*-$age = 5 case$age when 0 .. 2 puts"Infant"when 3 .. 6 puts"Child"when 7 .. 12 puts"child"when 13 .. 18 puts"Teenager"else puts"Other age group"end
[Try it Β»](#)
The output of the above example is:
Child
When the "expression" part of the case is omitted, the first when condition that evaluates to true is executed.
foo = false bar = true quu = false case when foo then puts'foo is true'when bar then puts'bar is true'when quu then puts'quu is true'end# Displays "bar is true"
YouTip