As the others have already explained, the only difference is the precedence. However, I would like to point out that there are actually two differences between the two:
and
, or
and not
have much lower precedence than &&
, ||
and !
and
and or
have the same precedence, while &&
has higher precedence than ||
In general, it is good style to avoid the use of and
, or
and not
and use &&
, ||
and !
instead. (The Rails core developers, for example, reject patches which use the keyword forms instead of the operator forms.)
The reason why they exist at all, is not for boolean formulae but for control flow. They made their way into Ruby via Perl's well-known do_this or do_that
idiom, where do_this
returns false
or nil
if there is an error and only then is do_that
executed instead. (Analogous, there is also the do_this and then_do_that
idiom.)
Examples:
download_file_via_fast_connection or download_via_slow_connection
download_latest_currency_rates and store_them_in_the_cache
Sometimes, this can make control flow a little bit more fluent than using if
or unless
.
It's easy to see why in this case the operators have the "wrong" (i.e. identical) precedence: they never show up together in the same expression anyway. And when they do show up together, you generally want them to be evaluated simply left-to-right.