MxLDevs
MxLDevs

Reputation: 19556

Using the && operator with non-boolean operands

What does the following piece of code mean, and why would someone write it like this?

a = 1
b = 2

if a && b != a 
   ...
end

What is the difference between that and just

if a != b
   ...
end

Upvotes: 1

Views: 65

Answers (2)

mdesantis
mdesantis

Reputation: 8517

if a checks for a to be truthy (neither nil or false):

a = 'a'
b = 'b'
if a && b != a
  puts "I will be printed"
end

a = false # or nil
b = 'b'
if a && b != a
  puts "I will NOT be printed"
end

Upvotes: 1

karthikr
karthikr

Reputation: 99680

a != b just checks if a and b are not equal,

where as a && b != a checks if a's truth value is True and a and b are unequal

An alternate way of representing this would be:

if a
    if b != a
        #Do something

Upvotes: 2

Related Questions