and, or, and not

Incidentally, Ruby has two different syntaxes for testing Boolean (true/false) conditions. In the previous example, I’ve used the English-language style operators: and, or, and not. If you prefer, you could use alternative operators similar to those used in many other programming languages, namely, && (and), || (or), and ! (not).

Be careful, though: The two sets of operators aren’t completely interchangeable. For one thing, they have different precedence, which means that when multiple operators are used in a single test, the parts of the test may be evaluated in different orders depending on which operators you use. For example, look at this test:

days.rb

if aDay == 'Saturday' or aDay == 'Sunday' and not working_overtime
   daytype = 'holiday'
end

Assuming that the Boolean variable working_overtime is true, would this test succeed if the variable aDay were initialized with the string “Saturday”? In other words, would daytype be assigned the value “holiday” if aDay is “Saturday”? The answer is no, it wouldn’t. The test will succeed only if aDay is either “Saturday” or “Sunday” and working_overtime is not true. So, when or is used in the previous code, Saturday would be deemed to be a working day.

Now consider this test:

if aDay == 'Saturday' || aDay == 'Sunday' &&  !working_overtime
   daytype = 'holiday'
end

On the face of it, this is the same test as the last one; the only difference is that this time I’ve used the alternative syntax for the operators. However, the change is more than cosmetic since if aDay is “Saturday,” this test evaluates to true and daytype is initialized with the value “holiday.” This is because the || operator has a higher precedence than the or operator. So, this test succeeds either if aDay is “Saturday” or if aDay is “Sunday” and working_overtime is not true. So, when || is used in the previous code, Saturday would be deemed to be a holiday.

Refer to Digging Deeper in Digging Deeper for more on this. As a general principle, you would do well to decide which set of operators you prefer—stick to them and use parentheses to avoid ambiguity.

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

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