Ruby Tutorial Ruby References

Ruby - If-Else Statements



If Statement

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

Syntax

if condition [then]
  statements
end

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

i = 15

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

The output of the above code will be:

15 is divisible by 3.

If-else Statement

The else statement can be used with if statement. It is used to execute block of codes whenever If condition gives false result.

Syntax

if 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

if 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.

elsif Statement

For adding more conditions, elsif statement in used. The program first checks if condition. When found false, it checks elsif conditions. If all elsif conditions are found false, then else code block is executed.

Syntax

if condition [then]
  statements
elsif condition [then]
  statements
...
...
...
else
  statements
end

In the example below, elsif statement is used to add more conditions between if statement and else statement.

i = 16

if (i > 25)
  puts "#{i} is greater than 25." 
elsif (i <=25 && i >=10)
  puts "#{i} lies between 10 and 25."
else
  puts "#{i} is less than 10."
end

The output of the above code will be:

16 lies between 10 and 25.

if modifier

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

Syntax

#single line statement
statement if condition

#multi-line statements
begin
  statements
end if condition

In the example below, the puts statement is executed only when the if condition is true.

i = 15

puts "#{i} is divisible by 3." if i % 3 == 0 

The output of the above code will be:

15 is divisible by 3.