Conditional Statements the many ways to test a condition: Lesson 7 of My Self-Inflicted Crash Course into Ruby

One of the most integral parts to programming is the basic IF statement or the conditional Statement. Ruby like most if not all languages uses the if keyword to define an IF statement. However it defers from other languages as you can use the if keyword as a statement or a modifier. In addition Ruby has the unless keyword to perform the else if logic without testing for a negative result.

The basic IF ELSE statement

The IF statement in Ruby is the same as Java or C++ with the following differences like methods you don’t need to utilize parenthesis and ELSE IF has been shortened into the elsif keyword. Lets start by looking at a basic example:

if var < 10 
    puts "The variable is less than ten."
elsif var >= 10 and var < 25
    puts "The variable is less than 25 but greater or equal to ten."
else
    puts "The variable is greater then or equal to 25."
end

The IF modifier

In addition to defining IF statements ruby lets you use conditionals as a modifier. For example you can write your command and append the if modifier so that the command only executes if the test conditional is true.

puts "The variable is less than 0" IF var < 0

In the example we have written our code for outputting our string but modified it by saying only output it IF our condition is met.

The UNLESS keyword

Ruby in addition to implementing the basic IF ELSE conditional has added in the unless keyword to their language. This keyword is used to say execute the following code if and only if this condition is not met.

if var < 0
    puts "The variable is greater than 0"
else
    puts "The variable is less than 0"
end

The unless keyword is really only a convenience method for those cases your are testing for false, so instead of negating the conditional statement you can simply use unless. Like the if keyword it can also be used as a modifier.

puts "The variable is less than 0" unless var >= 0

Not sure why it was determined that the unless keyword exists in Ruby as everything it can be used for can be completed with an if statement. However from what I have seen Ruby tries to let developers do whatever they want without imposing any restrictions so i guess writing unless is easier then a negated conditional for some.

// Ruby //

Comments & Questions

Add Your Comment