Ruby Conditionals

if - else

Example 1:if-else

puts "Hello, what's your name?"  
STDOUT.flush  
name = gets.chomp  
puts 'Hello, ' + name + '.' 
 
if name == 'chrys' 
    puts 'What a nice name!!' 
else 
    if name == 'chryz' 
        puts 'lame name!
   end 
end

Example 2:elseif

# Modified example with elseif 
puts "Hello, what's your name?"  
STDOUT.flush  
name = gets.chomp  
puts 'Hello, ' + name + '.'  
  if name == 'chrys'  
    puts 'What a nice name!!'  
elsif name == 'Sunil'  
        puts 'Another nice name!'  
end

Example 3: Same example with logical operators

# Further modified  
puts "Hello, what's your name?"  
STDOUT.flush  
name = gets.chomp  
puts 'Hello, ' + name + '.' 
 # || is the logical or operator 
if name == 'chrys' || name == 'chrys' 
    puts 'What a nice name!!'  
# end

unless

unless is the opposite of if. It executes code only if an associated expression evaluates to false or nil.

Example

unless ARGV.length == 2
  puts "usage: program.rb 23 35"
exit

Statement modifiers

Statement modifiers are a useful shortcut if the body of an if or while statement is just a single expression.

puts "Enrollments will now Stop" if participants > 2500

Case Expression

Example

year = 2000  
leap = case  
       when year % 400 == 0 then true  
       when year % 100 == 0 then false  
       else year % 4   == 0  
       end  
puts leap  
# output is: true
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.