Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

And Keyword in Ruby

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

The and keyword in Ruby takes two expressions and returns “true” if both are true, and “false” if one or more of them is false. This keyword is an equivalent of  && logical operator in Ruby, but with lower precedence. The main purpose of the and keyword is really to regulate control the flow of logic. You can use the and keyword for chaining operations that depend on each other.

Syntax:

 expression1 and expression2  

Example 1:

Ruby




# Ruby program to illustrate and keyword
username = "geek"
password = "come"
 
# Using and keyword
if username == "geek" and password == "come"
puts "Welcome, GeeksforGeeks!"
else 
puts "Incorrect username or password"
end


Output:

Welcome, GeeksforGeeks!

Example 2:

In this example, we will see the precedence difference in and keyword and && operator:

Ruby




# Ruby program to illustrate and keyword
# and && operator
 
def one() true; end
def two() true; end
 
# Using && operator
res1 = one && two ? "GeeksforGeeks" : "Do Nothing"
puts res1
 
# Using and keyword
res2 = one and two ? "GeeksforGeeks" : "Do Nothing"
puts res2


Output:

GeeksforGeeks
true

Explanation: In the above example, on the primary look the logic is the same, but we get different results. Because when you take a look closely, you will see the difference. In the first case output is GeeksforGeeks and in second case output is true. This is related, of course, with operator precedence. Think about the order in which they are evaluated (the precedence).

  1. &&
  2. =
  3. And

Here, the && has higher precedence than = in the first statement(i.e, using && operator) we have:

 res1 = one && two ? “GeeksforGeeks” : “Do Nothing”

In second statement(i.e, using and keyword), order of these operations is different = has higher precedence, then we have:

res1 = one and two ? “GeeksforGeeks” : “Do Nothing”

My Personal Notes arrow_drop_up
Last Updated : 13 Apr, 2021
Like Article
Save Article
Similar Reads