How to use the 'and' keyword in Ruby?

RubyServer Side ProgrammingProgramming

'and' Keyword in Ruby

In Ruby, we use the "and" keyword to return True if both the operands are true, and False if one or more of the operands is false. It should be noted that the and keyword is equivalent to the && logical operator, but it has lower precedence in Ruby.

Syntax

The syntax of the and keyword is shown below.

expression1 and expression2

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

Example

Consider the code shown below.

variable1 = "sunshine"
variable2 = "$un$h1ne"

# Using and keyword
if (variable1 == "sunshine" and variable2 == "$un$h1ne")
   puts "Learn Ruby Programming"
else
   puts "Variables Don't Match!"
end

Output

It will produce the following output.

Learn Ruby Programming

'and' and '&&' (logical and) Operator in Ruby

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

Example

Consider the code shown below.

# and && operator
def first() true; end
def second() true; end

# Using && operator
res1 = first && second ? "TutorialsPoint" : "Do Nothing"
puts res1

# Using and keyword
res2 = first and second ? "TutorialsPoint" : "Do Nothing"
puts res2

Output

If we write the following code on any Ruby IDE, then we will get the following output in the terminal.

TutorialsPoint
true

In the above code, when we use the and keyword, the output we got is "true", and that is because of the order of precedence of the "=" and the "and" keyword.

On the other hand, when we used the "&&" operator, we got "TutorialsPoint" as the output. This is because the precedence of the "logical and" operator (&&) is greater than the "and" keyword and also greater than the "=" operator.

raja
Updated on 12-Apr-2022 08:35:03

Advertisements