Step 10: Control Flow


Control Flow

So far we’ve learned about a few types of data, a few ways to manipulate that data, and how to store data within our program for later use. What about if we only want to carry out operations under certain circumstances?

awesome_number = 15 % 6


if awesome_number > 2
    puts("that number is greater than 2!")
else
    puts("that number is less than 2...or maybe it is 2")
end

In the example above, the string "that number is greater than 2!" will only be printed if the number calculated and stored in awesome_variable is greater than 2. The string "that number is less than 2...or maybe it is 2" will be printed in all other situations. We can extend this even further:

awesome_number = 15 % 6


if awesome_number > 2
    puts("that number is greater than 2!")
elsif awesome_number < 2
    puts("that number is less than 2!")
else
    puts("that number is clearly 2")
end

If/else control flow clauses must always contain an if to start and an end to close. They can contain zero to an unlimited number of elsif clauses, and zero or one (but not more than one) else clause.