Ruby If-else Statement

by

in

The Ruby if else statement is used to test condition. There are various types of if statement in Ruby.

  • if statement
  • if-else statement
  • if-else-if (elsif) statement
  • ternay (shortened if statement) statement

Ruby if statement

Ruby if statement tests the condition. The if block statement is executed if condition is true.

Syntax:

if (condition)  

//code to be executed  

end
Ruby if else 1

Example:

a = gets.chomp.to_i   

if a >= 18   

  puts "You are eligible to vote."   

end

Output:

Ruby if else 2

Ruby if else

Ruby if else statement tests the condition. The if block statement is executed if condition is true otherwise else block statement is executed.

Syntax:

if(condition)  

    //code if condition is true  

else  

//code if condition is false  

end
Ruby if else 3

Example:

a = gets.chomp.to_i   

if a >= 18   

  puts "You are eligible to vote."   

else   

  puts "You are not eligible to vote."   

end

Output:

Ruby if else 4

Ruby if else if (elsif)

Ruby if else if statement tests the condition. The if block statement is executed if condition is true otherwise else block statement is executed.


  1. if(condition1)  
  2. //code to be executed if condition1is true  
  3. elsif (condition2)  
  4. //code to be executed if condition2 is true  
  5. else (condition3)  
  6. //code to be executed if condition3 is true  
  7. end 
Ruby if else 5

Example:

a = gets.chomp.to_i   

if a <50   

  puts "Student is fail"   

elsif a >= 50 && a <= 60   

  puts "Student gets D grade"   

elsif a >= 70 && a <= 80   

  puts "Student gets B grade"   

elsif a >= 80 && a <= 90   

  puts "Student gets A grade"    

elsif a >= 90 && a <= 100   

  puts "Student gets A+ grade"    

end

Output:

Ruby if else 6

Ruby ternary Statement

In Ruby ternary statement, the if statement is shortened. First it evaluats an expression for true or false value then execute one of the statements.

Syntax:

  1. test-expression ? iftrue-expression : iffalse-expression  

Example:

var = gets.chomp.to_i;   

a = (var > 3 ? true : false);    

puts a

Output:

Ruby if else 7

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *