I wonder why ruby give and
, or
less precedence than &&
, ||
, and assign operator? Is there any reason?

- 78,216
- 16
- 166
- 166

- 8,036
- 11
- 48
- 84
5 Answers
My guess is that's a direct carry-over from Perl. The operators or
and and
were added later in Perl 5 for specific situations were lower precedence was desired.
For example, in Perl, here we wish that ||
had lower precedence, so that we could write:
try to perform big long hairy complicated action || die ;
and be sure that the ||
was not going to gobble up part of the action. Perl 5 introduced or
, a new version of ||
that has low precedence, for exactly this purpose.
An example in Ruby where you could use or
but not ||
:
value = possibly_false or raise "foo"
If you used ||
, it would be a syntax error.

- 158,662
- 42
- 215
- 303

- 76,767
- 18
- 98
- 146
-
Is there a name for the idiom of do_something or die? Does it get used in ruby? – Andrew Grimm Sep 17 '09 at 00:59
-
I don't know of any name for it, but it's fairly common in Ruby. – Chuck Sep 17 '09 at 03:08
-
Perl leans heavily on die, whereas Ruby uses raise. The advantage of an exception is you can rescue it. – tadman Sep 17 '09 at 15:20
-
Although technically you can rescue from a die, people don't usually bother unless it's really important. It's too much of a nuisance. – tadman Jul 12 '10 at 14:07
The difference is precedence. ||
, &&
have higher precedence than =
, but and
, or
have lower. So while you can do:
a = nil || 0
You would have to do:
a = (nil or 0)
to get same effect. If you do:
a = nil or 0
The result of expression would still be 0, but a value would be nil.

- 158,662
- 42
- 215
- 303

- 2,768
- 3
- 18
- 13
They have very low precedence so that the operands don't have to be wrapped in parentheses, as is sometimes the case with &&
and ||
.

- 158,662
- 42
- 215
- 303

- 234,037
- 30
- 302
- 389
Being able to control the precedence of your operators is sometimes useful, especially if you are concerned with readability -- extra parenthesis in conditional statements can sometimes obscure the actual logic.
To be frank, though, I think the reason Ruby has the boolean operator precedence levels it does stems mostly from the fact that Matz was a Perl programmer before he ever wrote Ruby, and borrowed much of the core syntax and operators from that language.

- 12,229
- 2
- 23
- 19
-
hmm, that explains why ruby is so immature and at the same time so much bloated. Still hard to wrap my head around that.. – akostadinov Jun 03 '14 at 16:37
I believe the idea is specifically to get them below the assignment operators, so you can write logic tests with assignments but without parens.

- 143,651
- 25
- 248
- 329