does anyone know the meaning of && and || when applied to integers in Ruby?
Here are some examples in IRB when && and || are applied to integers:
>> 1 && 2
=> 2
>> 2 && 1
=> 1
>> 15 && 20
=> 20
>> 20 && 15
=> 15
>> 0 && -1
=> -1
>> -1 && -2
=> -2
>> 1 || 2
=> 1
>> 2 || 1
=> 2
The boolean operators
&&
,||
,and
andor
are among the few that are not syntactic sugar for method calls, and thus, there are no different implementations in different classes.In other words: they behave exactly the same for all objects, i.e. they behave the same for
Integer
s as they do forString
s,Hash
es,Float
s,Symbol
s, and any other object.evaluates to
a
ifa
is falsey (and will not evaluateb
at all in this case), otherwise it evaluates tob
(and only then willb
be evaluated)evaluates to
a
ifa
is truthy (and will not evaluateb
at all in this case), otherwise it evaluates tob
(and only then willb
be evaluated)nil
andfalse
are falsey, everything else is truthy, including0
,0.0
,''
,[]
, and{}
.