Ruby Tutorial Ruby References

Ruby - Unless-Else Statements



Unless Statement

The Unless statement is used to execute a block of code when the condition is evaluated to be false. When the condition is evaluated to be true, the program will skip the unless-code block.

Syntax

unless condition [then]
  statements
end

In the example below, the unless code block is created which executes only when the variable i is divisible by 3.

i = 15

unless i % 3 != 0 
  puts "#{i} is divisible by 3."
end

The output of the above code will be:

15 is divisible by 3.

Unless-else Statement

The else statement can be used with unless statement. It is used to execute block of codes whenever unless condition gives true result.

Syntax

unless condition [then]
  statements
else
  statements
end

In the example below, else statement is used to print a message if the variable i is not divisible by 3.

i = 16

unless i % 3 != 0 
  puts "#{i} is divisible by 3." 
else
  puts "#{i} is not divisible by 3."
end

The output of the above code will be:

16 is not divisible by 3.

unless modifier

It executes the code if the condition is false. If the code contains multiple lines, it can be enclosed within begin and end statements.

Syntax

#single line statement
statement unless condition

#multi-line statements
begin
  statements
end unless condition

In the example below, the puts statement is executed only when the unless condition is false.

i = 15

puts "#{i} is divisible by 3.") unless i % 3 != 0 

The output of the above code will be:

15 is divisible by 3.