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
and or
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 for String
s, Hash
es, Float
s, Symbol
s, and any other object.
a && b
evaluates to a
if a
is falsey (and will not evaluate b
at all in this case), otherwise it evaluates to b
(and only then will b
be evaluated)
a || b
evaluates to a
if a
is truthy (and will not evaluate b
at all in this case), otherwise it evaluates to b
(and only then will b
be evaluated)
nil
and false
are falsey, everything else is truthy, including 0
, 0.0
, ''
, []
, and {}
.
来源:https://stackoverflow.com/questions/30478116/ruby-operator-on-integers