- Trending Categories
- Data Structure
- Operating System
- MS Excel
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to use the "or" keyword in Ruby?
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.
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!" else puts "Variables Don't Match! Please Check." end
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.
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 true
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.
- Related Articles
- How to use the "defined?" keyword in Ruby?
- How to use the "not" keyword in Ruby?
- How to use the 'and' keyword in Ruby?
- Yield keyword in Ruby Programming
- How to use BigDecimal in Ruby?
- How to use global variables in Ruby?
- How to Use Instance Variables in Ruby
- How to use the readonly keyword in TypeScript?
- How do I use Selenium with Ruby?
- How to use the 'break' and 'next' statements in Ruby?
- How to freeze objects in Ruby?