Hi,
I’m new to Ruby. Just started to take some online classes and now study
operators. Is there a difference if there is any between AND operator
“&&” and equality operator “==” ?
They are different. The equality operator is used to check that the values of two expressions are both the same, whereas the and operator is used to check if multiple expressions are true.
An expression using the equality operator is true if both sides of the ==
operator have the same value, e.g. 1 + 1 == 2
. Examples:
if 1 + 1 == 2
puts "You will see this."
end
if 1 + 1 == 3
puts "You will never see this."
end
An expression using the and operator is true if both sides of the &&
operator are true, e.g. 1 + 1 == 2 && 2 + 2 == 4
. Examples:
if 1 + 1 == 2 && 2 + 2 == 4
puts "You will see this."
end
if 1 + 1 == 3 && 2 + 2 == 5
puts "You will never see this."
end
if 1 + 1 == 2 && 2 + 2 == 5
puts "You will never see this."
end
In the last example, two plus two is not equal to five, so the right hand side of the total expression is false. Even though one plus one is equal to two, both sides are required to be true, so the total expression will be false.
The equality operator is a method which will return a true or false response.
1 == 2
# => false
2 == 2
# => true
Since it is a method you may write your own if you wanted.
The &&
operator is not a method. It will return the second object unless the first one is falsy. In Ruby nil
and false
are falsy objects, everything else is truthy.
4 && 5 # first item is true so return second item
# => 5
if 5
puts "hello"
end
# hello
4 && nil # first item is true so return second item
# => nil
if not 4 && nil
puts "The answer was falsy!"
end
# The answer was falsy!
false && true # The first item was not truthy so return the first item
# => false
2 chrisalley & danielpclark
Thank you for your detailed explanation. The difference is clear to me now