Day 3: Control Structures – Conditionals

Let’s imagine a highway. If a highway had no turns, then it could only lead us to one place. In order to have the ability to drive to different places using the same highway, we need to make turns.

Code gets executed line by line from top to bottom. It’s called a code flow. If you want to change the code flow, you need to use special keywords called Control Structures. There are two main categories of Control Structures: conditionals and loops

Conditionals

if

The “If” conditional is very dumb. If the code satisfies a condition, then run this code, otherwise run a different code. Here is the syntax:

today = "Friday"

if today == "Friday"
  puts "Time to party!"
else
  puts "Hang in there"
end

What does the code above do? On the first line, it defines the variable today and assigns it the value of “Friday”. Then, it evaluates the code inside the if condition. It tries to figure out whether the condition is true or false. If today is Friday then it’s true and the next line gets executed. You’ll see the text “Time to party!”. Yay!</span>

What happens next ? The code in the “else” clause gets skipped. It goes straight to the “end” clause which does nothing. Execution resumes after the “end” clause.

Guess what happens if today is not Friday. Then the condition is evaluated to false and it jumps to the line right after the “else” clause. You’ll see “Hang in there” and it goes to the “end” clause.

unless

The “unless” conditional acts in the opposite way of the “if” conditional. It evaluates a condition and does the opposite.

today = "Friday"

unless today == "Friday"
  puts "Keep calm and code on"
else
  puts "Almost there"
end

Let’s run it. If today is Friday then you’ll see “Almost there”. Why ? Because we used “unless” instead of “if”. If the “unless” keyword makes code a little confusing, try to read it as “if not”. You can read the code above as the following.

If not today is Friday, then “Keep calm and code on”, otherwise output “Almost there”

Photo by sacks08