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 run this program you'll see nothing gets printed. This is because both the statements are not true, but only one is true. That is, x is not equal to y, but x is equal to z. Since the && symbol means that both statements need to be true, the message was not printed.

Now, if I change && to ||, then we are asking Ruby to print the message if only one statement is true. In other words, || stand for OR while && stands for AND:

if x == y || x == z 
puts "from the if statement"
end

Since only one condition has to be true, this version of the program will print the text:

Technically, you can replace the symbols with the or and and words, but there are some small differences that can throw errors, so I prefer to use the symbols. So, this is how you can implement compound conditionals in Ruby.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.162.65