How to write if-else statement in Ruby?

You can use this statement in various format. like,

  1. if statement
  2. if-else statement
  3. elsif statement
  4. ternary statement

if statement:

Execute if block if condition is true. Check syntax here:

if (condition)  
//code to be executed  
end

See this example,

a = gets.chomp.to_i
if a > 3
   puts 'lets go to school'
end  

Output:

5
lets go to school

if-else statement:

Execute if block if condition is true. Otherwise, execute else block. Check syntax here,

if(condition)  
  //code if condition is true  
else  
  //code if condition is false  
end  

See this example,

a = gets.chomp.to_i
if a > 3
   puts 'lets go to school'  
else
	puts 'you are a baby child'
end

Output:

--------1st output-------
5
lets go to school

-------2nd output--------
2
you are a baby child

elsif statement:

Execute if block if condition is true. Otherwise, execute else block. Check syntax here,

if(condition1)  
//executed if condition1 is true  
elsif (condition2)  
//executed if condition2 is true  
else (condition3)  
//executed if condition3 is true  
end

See this 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:

Ternary statement:

The if statement is shortened. First it evaluates an expression for true or false value then execute one of the statements. Check syntax here:

test-expression ? iftrue-expression : iffalse-expression  

See this Example:

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

Output:

I hope you guys found this page helpful 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.