Nested if...else conditionals
In this section, we are going to extend our knowledge of conditionals by learning about the if...elsif
mechanism. This tool allows us to set up multiple conditional scenarios for our programs to manage data flow. Ruby has a slightly odd syntax on this functionality, so let's walk through it one step at a time.
The if...elsif conditional code example
To review, I'm going to start off with a regular if
statement:
x = 10 y = 100 z = 10 if x == y puts "x is equal to y" end
If you run this program, nothing will print out since x
is not equal to y
. This is what you already know. Now, I'm going to add some additional scenarios:
if x == y puts "x is equal to y" elsif x > z puts "x is greater than z" else puts "Something else" end
Essentially, this code is going to check if x
is equal to y
, and if it's not, it moves down to the next condition and checks if x
is greater than z
, which if not true again means that, it finally prints Something else
. Whenever...