🚀Intermediate Ruby: understanding conditionals and loops in Ruby

Dumebi Okolo - Oct 30 '23 - - Dev Community

Hi and welcome!
In this today's class, I have learned about conditionals and loops in Ruby. This article will talk about conditional statements and loops in Ruby.

Table of Contents

 1. What are conditional statements?
 2. Conditional statements in Ruby

       2.1. if/else statements in Ruby

             a. Nested if statements in Ruby

       2.2. Unless statements in Ruby

             b. Unless... then statements

       2.3. Case conditionals in Ruby
 3. Loops in Ruby

       3.4. While loops in Ruby

             c. Until loops in Ruby

       3.5. The for loop in Ruby
 4. References

What are conditional statements?

As gotten from wikipedia:

In computer science, conditionals are programming language commands for handling decisions. Specifically, conditionals perform different computations or actions depending on whether a programmer-defined Boolean condition evaluates to true or false.

Simply put, conditional statements are keywords in any programming language that check the truthy value of a code block before executing the enclosed commands.
That is, do this while this is true, and if it is false, do that.

Conditional statements in Ruby

In Ruby, we have the following conditional statements or pairs:

  • if ... else conditional blocks
  • unless statements
  • unless ... then.
  • case ... when.

if/else statements in Ruby

ruby if/else

The if/else statements in Ruby are basically what the English equivalent is.
That is,
if X is true, perform Y. Else, perform Z.
Ruby exits conditional blocks with end keyword.
Here is an example:


a = 5
b = 6
if a < b
puts "a is less than b."
else 
puts "b is greater than a."
end

#output=> "a is less than b."
Enter fullscreen mode Exit fullscreen mode

We see here that our output became "a is less than b." because Ruby parsed through our code and determined that a=5 is less than b=6, which satisfies the condition we gave, if a < b.
If, in our code, a was 7, making a greater than b=6, our output will instead be "b is greater than a" because Ruby has parsed through out code to find that the conditional statement was false.

In conjunction with if..else keywords, Ruby also has another keyword: elsif.
The elsif keyword can be seen to mean "else if". We use this keyword after an if statement has already been declared, but we also want to add another conditional to produce an end result or output.
From our previous example:


a = 5
b = 6
if a < b
puts "a is less than b."
elsif a = b
puts "a is equal to b."
else 
puts "b is greater than a."
end

#output=> "a is less than b."

Enter fullscreen mode Exit fullscreen mode

We see from the above that the elsif keyword introduced a new conditional statement to be parsed through in determining the final end result.

Nested if statements in Ruby

In Ruby, it is also possible that we nest if statements in other if statements.
We do this because when Ruby encounters a conditional block, it parses through the various conditions to pick ONE possible outcome depending on the truthy value of the proposed condition.
However, when writing code; there are situations where we have will have conditions that depend on the "bigger" condition and we will also like to have multiple outcome based on the different conditions.

Here's an example:

print 'Number 1:'
a = gets.chomp
print 'Number 2:'
b = gets.chomp
print 'Do you want to compare>'
answer = gets.chomp
if answer== 'yes'
  puts 'beginning computation...'
  if a > b
    puts "#{a} is greater than #{b}."
  elsif a < b
    puts "#{a} is less than70
 #{b}."
    end
    if a != b
      puts "#{a} is not equal to #{b}"
      end
      if a.to_i % 2 == 0 and b.to_i % 2 == 0
      puts "#{a} and #{b} are even numbers."
      # elsif b.to_i % 2 == 0
      #   puts "#{b} is an even number"
      elsif a.to_i % 2 > 0 and b.to_i % 2 > 0
        puts "#{a} and #{b} are odd numbers."
        elsif a.to_i % 2 > 0 or b.to_i % 2 == 0
          puts "#{a} is an odd number while #{b} is an even number"
        elsif a.to_i % 2 == 0 or b.to_i % 2 > 0
          puts "#{b} is an odd number while #{a} is an even number"
        end
else
  puts 'Your loss'
  end

Enter fullscreen mode Exit fullscreen mode

Ruby if/else statement example

In the example above, we see a working together of everything we have learned so far in Ruby. From last week's article, we learnt about different string properties which we have used in the example above. We also used our knowledge of if/else statements.
On the left-hand side of the image above, we see the output of the code we just ran.

Unless statements in Ruby

Now, I had a bit of an issue understanding the unless statement. I understood what it was, but I needed a simple way to explain away the logic.

unless statements default to false.

Let me explain:

If you have a problem,

a = 5
unless a > 6 
puts 'a is greater than 6.'
end

#output=> "a is greater than 6."
Enter fullscreen mode Exit fullscreen mode

We have this output or result because the statement a = 5 > 6 is false. unless conditional blocks also have else statements in them.

Unless... then statements

Another way to use or write unless conditional blocks is by writing it as a one-liner using the then keyword.
We usually use this when the value of a variable depends on a condition.


is_available = false

greetings = unless is_available then 'User is unavailable' end
puts statement. 

#output=> "User is unavailable."
Enter fullscreen mode Exit fullscreen mode

Case conditionals in Ruby

Another set of conditional statements in Ruby that we can use to avoid verbosity in our code are the case ... when statements.
They work very similarly to the if ... else statements.
The major difference here is that case statements take up fewer lines of code.

print 'Input exam score:'
score = gets.chomp

case score.to_f
when 0..34 then puts 'You got an F!' #the .. expression is used to represent ranges
when 35..44 then puts 'You got an E!'
when 45..49 then puts 'You got a D!'
when 50..59 then puts 'You got a C!'
when 60..69 then puts 'You got a B!'
when 70..100 then puts 'You got an A!'
else puts 'Score must be a number less than or equal to 100'
end
Enter fullscreen mode Exit fullscreen mode

case in ruby

Case conditional blocks start with the case keyword followed by the statement we want to check the truth of against some conditions. In the case of the above example, we want it to examine the score input we get returned as a float.
When the statement to be examined has been given, we go ahead and tell the computer program what to do when any of the conditionals have been met.
From the example above, after parsing through the case that is to be evaluated, the computer program checks each of the when ... then statements to determine exactly how true it is.
We see that this works similar to using a combination of if, elsif, and else keywords in a block. It is just shorter, cleaner, and easier to understand.

Loops in Ruby

Loops are a programming element that repeat a portion of code a set number of times until the desired process is complete.
That is, loops are codes or code blocks we write to make sure that a certain thing keeps repeating itself given that a certain condition is true or never runs out.
In Ruby, we have the while and until keywords for determining loops.

While loops in Ruby

The while keyword is pretty self-explanatory from the English meaning. We are simply telling our computer code to keep doing something WHILE a condition remains true.
If we were just to leave a loop block without defining a 'stop button' for it, our loops will run infinitely and we don't want that to happen.


i = 0

while i < 5
puts i
i +=1
end

#output=>
0
1
2
3
4
Enter fullscreen mode Exit fullscreen mode

In the example above, we see that we first defaulted i to be equal to 0. We want the computer to output i for us while 0 remains less than 5. If we just left the statement at this, the loop will run forever because 0 will always be less than 5. However, we introduced a 'stop button' which is telling our computer program to keep incrementing i. It will keep incrementing i till it satisfies our condition that i has to be less than 5. This is why our output stops at 4, because anything more than that will be negating our condition.

REMEMBER TO ALWAYS PUT AN end STATEMENT AT THE END OF ANY CONDITIONAL OR LOOP BLOCK.

Until loops in Ruby

We will replicate the example we used above here:

i = 0
until i > 5
put i
i += 1
end

#output=> 0
1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

We can see from this example that the command we asked the computer program is to (continue to) output i UNTIL i becomes greater than 5.

The for loop in Ruby

The for loop is used to iterate over a set of values.

for loops in Ruby

for i in 1..10 do
puts i

end

#output=> 
1
2
3
4
5
6
7
8
9
10
Enter fullscreen mode Exit fullscreen mode

We see in the example above that we asked the computer program to loop through i in the range of 1 to 10 and then print out every value of i, which is from 1 to 10.

There are more loops in Ruby, but this is where we will be stopping for now.
That's all for today's class on Ruby. See you in the next tutorial.
Connect with me on LINKEDIN
Follow me on X (formerly twitter)

References

image: if/else in ruby
image: for loops in ruby
cover image

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .