Guide to compound conditionals
So far in this section we have seen if
, unless
, if...else
, and if...elsif
statements and how they work in Ruby programs. Additionally, there are times when you may want to combine multiple conditionals together to enable a more granular data check. In this guide, I will show you how to utilize multiple conditionals per line.
Compound conditionals code example
Let's say you want to check for two nested conditions. Technically, you could accomplish the desired output with this code:
x = 10 y = 100 z = 10 if x == y if x == z puts "equal to everything" end end
This code checks if x
and y
are the same, and if true, also checks if x
and z
are the same. If the nested condition is also satisfied, then it prints equal to everything
.
Even though this works, it's pretty ugly and could lead to code that's hard to read and debug. Thankfully, there is another way to create the same behavior:
if x == y && x == z puts "from the if statement" end
If you...