Control Statements in Ruby

if and unless:

The first use of if :
age = 10
puts “You’re too young to use this system” if age < 18
If the value of age is under 18, the string is printed to the screen. It has the following syntax:

age = 10
if age < 18
puts "You're too young to use this system"
end

elsif:

Sometimes it’s desirable to make several comparisons with the same variable at the same time. You could do this with the if statement.

fruit = "orange"
color = "orange" if fruit == "orange"
color = "green" if fruit == "apple"
color = "yellow" if fruit == "banana"

If you want to use else to assign something different if the fruit is not equal to orange, apple, or banana, it will quickly get messy, as you’d need to create and if block to check for the presence of any of these words, and then perform the same comparisons as earlier. An alternative is to use elsif, meaning “else if ”:

Example:

fruit = "orange"
if fruit == "orange"
color = "orange"
elsif fruit == "apple"
color = "green"
elsif fruit == "banana"
color = "yellow"
else
color = "unknown"
end

case:

A case block works by processing an expression first, and then by finding a contained when block that matches the result of that expression. If no matching when a block is found, then the else block within the case block is executed instead.

Example:

fruit = "orange"
case fruit
when "orange"
color = "orange"
when "apple"
color = "green"
when "banana"
color = "yellow"
else
color = "unknown"
end