Is there any wisdom behind “and”, “or” operators in Ruby?

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

Answers 1

  • 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.


Related Articles