How to Use the “or” Keyword in Ruby?

Learn via video courses
Topics Covered

Overview

The or keyword in Ruby is an operator used to express conditional logic. You can use it to compare two expressions and return the first true value. This keyword is particularly useful when working with default values and conditional expressions. This article will introduce the or keyword in Ruby, explain its syntax, provide examples of how we can use it, discuss the difference between Ruby or and logical or (||), and provide best practices for using the Ruby or operator in your code.

Pre-requisites

A basic understanding of Ruby syntax and control structures is essential before diving into the Ruby or keyword. It would also be beneficial to have familiarity with Ruby conditional statements and boolean logic.

Introduction to or Keyword in Ruby

The or keyword is used in Ruby to express a logical disjunction. Control structures often use it to set default values or provide a fallback option when a certain condition is unmet. The or keyword is similar to the || operator in other programming languages and provides a convenient shorthand for conditional expressions.

Syntax

The syntax for using the Ruby or operator is straightforward. The keyword is simply placed between two expressions that you want to evaluate. For example, consider the following code snippet:

Ruby OR Syntax:

In this example, the variable x is set to nil, the variable y is set to 10, and the Ruby or keyword is used to evaluate the expressions x or y. Since x is nil (which denotes a false value in Ruby), the or keyword will evaluate the expression and return the value of y. Thus, the variable z will be assigned the value 10.

Examples

We can use the or keyword in Ruby in the following ways:

Example 1: Setting Default Values

Code:

Output:

In this example, the or keyword provides a default value for the name variable. If name is nil, then the second expression (name or "World") will be evaluated and concatenated with the "Hello, " string. Thus the or keyword is used to assign a default value to a variable if its current value is nil.

Example 2: Providing Fallback Options

Code:

Output:

In this example, the || operator is used as an alternative to the or keyword. The expression x || y is equivalent to x or y. Since x is nil, the || operator will evaluate the second expression y, and z will be assigned the value 10. This provides a fallback option if the first value is not suitable or unavailable, and the second value can be used as an alternative.

Example 3: Setting multiple default values

Code:

Output:

In this example, the or keyword sets default values for multiple variables. If any of the variables are nil, the or keyword will evaluate the second expression (1, 2, or 3).

Difference Between Ruby "or" and Logical "or"

In Ruby, there are two operators that can be used for logical disjunction: the or operator and the || (double pipe) operator. While they may seem interchangeable, the two have some important differences.

Operator Precedence

The main difference between the two operators is their operator precedence. The or operator has a lower precedence than most other operators, including the && (logical and) operator and the || operator. This means that expressions with or will be evaluated after expressions with these other operators. For example:

Code:

Output:

Explanation of the output: In this case, the output is false because the or operator has lower precedence than the || operator. So the expression true || false is evaluated first, which results in true. Then the expression x = false or true is evaluated. Since the or operator has lower precedence than the = operator, so the expression x= false is evaluated first and x is assigned the value false, and then the second expression is evaluated which returns the value true. Since there is no variable to catch that value, the true value returned from there is discarded.

If we add parentheses to the expression, we can change the order of evaluation:

Code:

Output:

In this case, the parentheses change the order of execution and force the false or true expression to be evaluated first, which results in the value true. After that, the || operator is evaluated with the values true and false, resulting in the value true. Thus, the variable x gets the value true.

So, as we can see, the order of evaluation of operators can significantly affect the final result of the expression, and it is important to be aware of the precedence rules of different operators to write correct and unambiguous code.

Short-Circuit Evaluation

Another important difference between Ruby and || operators is their short-circuit evaluation behavior. The || operator will short-circuit if its left operand is true, meaning that it won't evaluate the right operand. This can be useful in cases where the right operand may have side effects or may be expensive to evaluate. For example:

Code:

In this case, if true is encountered, the expensive_operation() function will not be called. However, with the or operator, both operands will always be evaluated, regardless of the left operand's truth value:

Code:

In this case, the expensive_operation() function will always be called, regardless of the value of true taken by the first expression.

When to Use Each Operator

In general, the || operator is more commonly used in Ruby code than the or operator. This is because the || operator has higher precedence and short-circuits when its left operand is true, making it more efficient and less error-prone in many cases.

However, there are some cases where the or operator may be more appropriate. For example, if you need to chain several expressions together and don't want to use parentheses, the or operator can be useful for separating the expressions:

Code:

In this case, the or operator provides a clean way to chain several expressions together without needing to use parentheses.

Best Practices for Using Ruby or

When using Ruby or operator, the following are some of the best practices that should be kept in mind:

Use Parentheses to Ensure the Right Order of Evaluation

Because the or operator has lower precedence than many other operators, it's important to use parentheses to ensure that expressions are evaluated in the correct order. For example:

Code:

This expression will evaluate as true because the || operator has higher precedence than or. However, if we want to evaluate the or expression first, we need to add parentheses:

Code:

Be Careful With Side Effects

Because the or operator always evaluates both operands, it's important to be careful when using it with expressions that have side effects. For example:

In this case, both function1() and function2() will be called, regardless of the value of function1().

Another example where the difference between or and || is important is in assigning default values to variables. Consider the following code snippet:

Code:

In this case, the value of username will be nil. However, if we use the || operator instead of or, the value of username will become default_username. This is because the || operator has higher precedence than the assignment operator, so the expression is evaluated as follows:

Since name is nil, the expression evaluates to default_username which is then assigned to the username variable. However, if we use or instead, the expression is evaluated as follows:

Code:

Since name is nil, the first part of the expression assigns nil to the name variable, and then default_username is evaluated and discarded.

Use or for Control Flow

One of the most common use cases for the or keyword is for control flow. As we've seen in the examples above, or can be used to chain together expressions in a way that allows us to take different actions based on the outcome of each expression.

Keep It Simple

In general, it's best to keep your use of or simple. Avoid using it for complex or convoluted expressions that are difficult to read and understand.

Use Parentheses to Clarify Your Intentions

If you're unsure whether your use of or will be clear to other developers who may read your code, use parentheses to explicitly group the expressions and clarify your intentions.

Be Consistent

Finally, be consistent in your use of or throughout your codebase. Consistency makes it easier for other developers to read and understand your code and reduces the risk of errors and bugs.

Conclusion

  • The or operator in Ruby is a powerful operator that allows you to write concise and readable code. By using or in your code, you can reduce the number of conditional statements and make your code more maintainable.
  • In this article, we've explored the or keyword in Ruby and how it differs from the || operator.
  • We've seen how or can be used for control flow and assignment and discussed best practices for using or effectively.
  • By following these guidelines, you can use or to write clear, concise, and effective Ruby code.