How to use the "or" keyword in Ruby?

RubyServer Side ProgrammingProgramming

In Ruby, we use the "or" keyword to return the logical difference between its two operands. In simple terms, we can say that a condition becomes True if both the operands are true.

  • "or" returns True if any one of the conditions/expressions is "true".

  • It returns False only when all the conditions are "false".

It should be noted that the or keyword is equivalent to the "||" logical operator, but it has lower precedence in Ruby.


The syntax of the or keyword is shown below.

Condition1 or Condition2

Let's use the or keyword in a Ruby code and see how it works.

Example 1

Consider the code shown below.

variable_1 = "Naresh"
variable_2 = "Naresh"

# Using or keyword
if (variable_1 == "naresh" or variable_2 == "N@re$h")
   puts "Welcome to TutorialsPoint!"
   puts "Variables Don't Match! Please Check."


It will produce the following output in the terminal.

Variables Don't Match! Please Check.

In the above example, we declared an if condition, where we used the or keyword.

Example 2

Now, let's use the or keyword and the "logical or" (||) operator to see how it is different and in what scenarios we should choose one over the other. Consider the code shown below.

# and || operator

def first_method() true; end
def second_method() false; end

# Using || operator
res1 = first_method || second_method ? "Code in Ruby" : "Code in Java"
puts res1

# Using or keyword
res2 = first_method or second_method ? "Code in Ruby" : "Code in Java"
puts res2


When we execute this code, it will produce the following output

Code in Ruby

In the above code, when we used the or keyword, we noticed that the output we got is True, and that is because of the order of precedence of the "=" and the "or" keyword.

When we used the "logical or" (&&) operator, its precedence is greater than the or keyword and also the "=" operator, that's why, we got the above output.

Updated on 12-Apr-2022 08:45:00