Ruby Simplified Part 3: Ruby conditional statements

Let’s look at some conditional statements in Ruby, if-else, case, and unless.

=begin
A simple program to test user input,
notice that this comment is multiline
=end

# If-Else statement
puts "Please input number..."
x = gets        # Get user input
x = x.chomp     # Chop off the '\n' at the end
x = x.to_i      # convert the string into an integer

if (x < 0) 
    puts "user input " + x.to_s + " is negative"    # convert integer into string with .to_s
elsif (x == 0)
    puts "user input " + x.to_s + " is zero"
else
    puts "user input " + x.to_s + " is positive"
end

# The 'if' modifier
puts "Writes this line only if x is 1" if x == 1

# Case statement
puts "Please input another number..."
x = gets.chomp.to_i     # Notice how we shorten the operations

case
    when x < 0 
        puts "user input " + x.to_s + " is negative" 
    when x == 0
        puts "user input " + x.to_s + " is zero"
    when x > 0
        puts "user input " + x.to_s + " is positive"
end

# Unless statement
puts "Please input another number..."
x = gets.chomp.to_i

unless x > 0        # The equivalent of 'unless' is the if(!...) in C#
    unless x == 0
        puts "user input " + x.to_s + " is negative"
    else
        puts "user input " + x.to_s + " is zero"
    end
else
    puts "user input " + x.to_s + " is positive"
end

# Unless conditional
puts "Write this line unless x is 0, meaning, if x is 0 then don’t write this line" unless x == 0

# Anything inside 'BEGIN' is called before the program is run
BEGIN { puts "Simple program to test user input." }

# Anything inside 'END' is called after the program is run
END { puts "All done!" }
Advertisements

About soumya chattopadhyay
I live and work in Seattle, WA. I work with Microsoft technologies, and I'm especially interested in C#.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: