The Ternary Operator and the OR Operator

The ternary operator is not reasonable for a situation that returns true or false; if the goal is to get a result of true or false from your decision, it is better to simply evaluate the statement itself.

For example, if it reduces to this statement: some_condition ? true : false then you are better off just simply using some_condition by itself, as it will evaluate to either true or false.

If, however, you have a statement that evaluates such as

some_condition ? true : (some_action or other value)

What you may be asking for and really wanting is the OR Operator, rather than the ternary:

some_condition || do_this_if_"some_statement"_evaluates_as_false

If this doesn’t immediately look familiar, look at this:

assign_this = evaluated_condition ? true : expression_if_evaluated_statement_is_false

Is the same as:

assign_this = evaluated_statement_if_true or expression_if_evaluated_statement_is_false

On the other side of the spectrum, when you have

some_statement ? (some_action or other value) : false # or nil You will want to use the AND operator:

some_condition && do_this_if_some_condition_evaluates_as_true

Rather than using the ternary with a false return like:

assign_this = evaluated_condition ?  (some_action or other value)  : false

Remember, the point of either is having an evaluated statement that has the possibility of being false (or nil) as well as the possibility of being true.

If your evaluated statement never has both possibilities, then these aren’t the operators for you at this moment.

In conclusion, we use the ternary operator when we have a simple if..then operation that does not return either true or false itself. We use the or and and operator when we need one evaluation or the other. When using the ternary operator, we don’t use it to return true or false, there are easier ways to do that.

The discussion starts here, but continues in our Google Plus Post!