Philipp Antar
Philipp Antar

Reputation: 182

Ruby logical "and" operator

When playing with IRB I came across this:

a = -1
b = 1
(a and b) > 0

returns true, however

(false and true) == true

returns false.

Why does the first statement return true? In the 'pickaxe' I read "Both and and && evaluate to true only if both operands are true. They evaluate the second operand only if the first is true[...]"

This implies -- to me -- that the first statement should return false

Upvotes: 1

Views: 5426

Answers (3)

jvnill
jvnill

Reputation: 29599

in ruby, the only time an object is false is if it is false or nil.

>> !!nil # false
>> !!false # false
>> !!-1 # true

in your syntax, it is impossible to get what you want to say when you try

>> (1 and -1) > 0

since and should be used to return true or false but what I found interesting is the value returned

>> (1 and -1) # -1
>> (-1 and 1) # 1

so having (b and a) > 0 would return false which is interesting

(1 and -1) will return -1 since the and operator needs to satisfy all conditions. there's something wrong with me today.

Upvotes: 0

quetzalcoatl
quetzalcoatl

Reputation: 33516

Why should it be false? Both operands a and b are not false, and even not nil..

IIRC, in Ruby, every value different than false/nil is considered true. Even zero. Hence 0 and 0 is true. -1 and 1 surely too!

EDIT: aah, I just grasped what you meant. You mean that the first expression -1 and 1 should return -1? No, that's what OR does!

-1 and 1   =>  1
-1 or 1    => -1

AND evaluates ALL operand for 'true' result, and reduces checks only if one item is 'false'.
OR evaluates ALL operand for 'false' result, and reduces checks only if one item is 'true'

Upvotes: 3

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

Both -1 and 1 are "truthy" values from ruby's point of view. That's why

-1 and 1 # => 1
false and true => false

that the first statement should return false

I don't see where you got this from. Aren't you confusing it with OR operator?

a = -1
b = 1

a and b # => 1
(a and b) > 0 # => true

a && b # => 1
(a && b) > 0 # => true

a || b # => -1
(a || b) > 0 # => false

Upvotes: 3

Related Questions