Ruby If Else

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Ruby If-else Statement

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:

  1. if (condition)  
  2. //code to be executed  
  3. end  

Ruby if else 1

Example:

  1. a = gets.chomp.to_i   
  2. if a >= 18   
  3.   puts "You are eligible to vote."   
  4. 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:

  1. if(condition)  
  2.     //code if condition is true  
  3. else  
  4. //code if condition is false  
  5. end  

Ruby if else 3

  Example:

  1. a = gets.chomp.to_i   
  2. if a >= 18   
  3.   puts "You are eligible to vote."   
  4. else   
  5.   puts "You are not eligible to vote."   
  6. 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.

Syntax:

Ruby if else 5

Example:

  1. a = gets.chomp.to_i   
  2. if a <50   
  3.   puts "Student is fail"   
  4. elsif a >= 50 && a <= 60   
  5.   puts "Student gets D grade"   
  6. elsif a >= 70 && a <= 80   
  7.   puts "Student gets B grade"   
  8. elsif a >= 80 && a <= 90   
  9.   puts "Student gets A grade"    
  10. elsif a >= 90 && a <= 100   
  11.   puts "Student gets A+ grade"    
  12. 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 ? if-true-expression : if-false-expression  

Example:

  1. var = gets.chomp.to_i;   
  2. a = (var > 3 ? true : false);    
  3. puts a 

Output:

Ruby if else 7