🚀Intermediate Ruby: understanding conditionals and loops in Ruby
Tags: webdev, ruby, beginners, tutorial
Published: 2023-10-30 10:24:38

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
&nbsp;1. [What are conditional statements?](#what-are-conditional-statements)
&nbsp;2. [Conditional statements in Ruby](#conditional-statements-in-ruby)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 2.1. [if/else statements in Ruby](#ifelse-statements-in-ruby)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; a. [Nested if statements in Ruby](#nested-if-statements-in-ruby)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 2.2. [Unless statements in Ruby](#unless-statements-in-ruby)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; b. [Unless... then statements](#unless-then-statements)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 2.3. [Case conditionals in Ruby](#case-conditionals-in-ruby)
&nbsp;3. [Loops in Ruby](#loops-in-ruby)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3.4. [While loops in Ruby](#while-loops-in-ruby)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; c. [Until loops in Ruby](#until-loops-in-ruby)

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3.5. [The for loop in Ruby](#the-for-loop-in-ruby)
&nbsp;4. [References](#references)

## What are conditional statements?

As gotten from [wikipedia](https://en.wikipedia.org/wiki/Conditional_(computer_programming)):

> 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q40985mv852d58rrqa6l.jpg)

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:

```ruby

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."
```
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:

```ruby

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."

```

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:

```ruby
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

```


![Ruby if/else statement example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1ma37wdwonxymhvmmz6z.png)

In the example above, we see a working together of everything we have learned so far in Ruby. From [last week's article](https://dev.to/dumebii/an-introduction-to-ruby-33fk), 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,

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

#output=> "a is greater than 6."
```

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.

```ruby

is_available = false

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

#output=> "User is unavailable."
```

### 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.

```ruby
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
```


![case in ruby](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/txogr6cq67mf8wlo41hb.png)

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. 

```ruby

i = 0

while i < 5
puts i
i +=1
end

#output=>
0
1
2
3
4
```
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:

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

#output=> 0
1
2
3
4
5
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rkcknfbf12ys3ady8yc6.jpg)

```ruby
for i in 1..10 do
puts i

end

#output=> 
1
2
3
4
5
6
7
8
9
10
```

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](www.linkedin.com/in/dumebi-okolo)
Follow me on [X (formerly twitter)](https://twitter.com/DumebiTheWriter) 
 
##References
[image: if/else in ruby](https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.educba.com%2Fruby-if-else%2F&psig=AOvVaw2ELQWbKLSD4U_KOcwuOjJY&ust=1698746636188000&source=images&cd=vfe&opi=89978449&ved=0CBQQjhxqFwoTCIiDqMTCnYIDFQAAAAAdAAAAABAE)
[image: for loops in ruby](https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.educba.com%2Ffor-loop-in-ruby%2F&psig=AOvVaw323DkJ6uC7c6z7jAOCGxsH&ust=1698746798769000&source=images&cd=vfe&opi=89978449&ved=0CBIQjRxqFwoTCIiNlI_DnYIDFQAAAAAdAAAAABAZ)
[cover image](https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.geekboots.com%2Fstory%2F10-reasons-to-start-learning-ruby&psig=AOvVaw26pnOpjYY2mAz38gApzn8W&ust=1698747257106000&source=images&cd=vfe&opi=89978449&ved=0CBQQjhxqFwoTCPCinOnEnYIDFQAAAAAdAAAAABAE)