Conditionals

If this is true, then do that. Otherwise do something else.

Often we want to check for a certain condition, and then based on it, do either one thing or another. Or we want to do something only if a condition is true.

All practical programming languages have some way of expressing this, and in Ruby it looks like so:

number = 5

if number.between?(1, 10)
  puts "The number is between 1 and 10"
elsif number.between?(11, 20)
  puts "The number is between 11 and 20"
else
  puts "The number is bigger than 20"
end

You can probably guess what it does, and how it works, can’t you?

Let’s walk through it one by one:

The elsif and else statements and branches are optional: you don’t need to have them. You can have an if statement without elsif or else branches, an if statement only with an else, or you could have an if statement with one or more elsif statements. Or combine all of them together: