What is the difference between the &&
and and
operators in Ruby?
||
and &&
bind with the precedence that you expect from boolean operators in programming languages (&&
is very strong, ||
is slightly less strong).
and
and or
have lower precedence.
For example, unlike ||
, or
has lower precedence than =
:
> a = false || true
=> true
> a
=> true
> a = false or true
=> true
> a
=> false
Likewise, unlike &&
, and
also has lower precedence than =
:
> a = true && false
=> false
> a
=> false
> a = true and false
=> false
> a
=> true
What's more, unlike &&
and ||
, and
and or
bind with equal precedence:
> !puts(1) || !puts(2) && !puts(3)
1
=> true
> !puts(1) or !puts(2) and !puts(3)
1
3
=> true
> !puts(1) or (!puts(2) and !puts(3))
1
=> true
The weakly-binding and
and or
may be useful for control-flow purposes: see http://devblog.avdi.org/2010/08/02/using-and-and-or-in-ruby/ .