I wonder why ruby give and
, or
less precedence than &&
, ||
, and assign operator? Is there any reason?
相关问题
- How to specify memcache server to Rack::Session::M
- Why am I getting a “C compiler cannot create execu
- reference to a method?
- ruby 1.9 wrong file encoding on windows
- gem cleanup shows error: Unable to uninstall bundl
相关文章
- Ruby using wrong version of openssl
- What does it means in C# : using -= operator by ev
- Difference between Thread#run and Thread#wakeup?
- how to call a active record named scope with a str
- C# generics class operators not working
- “No explicit conversion of Symbol into String” for
- Segmentation fault with ruby 2.0.0p247 leading to
- How to detect if an element exists in Watir
My guess is that's a direct carry-over from Perl. The operators
or
andand
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:and be sure that the
||
was not going to gobble up part of the action. Perl 5 introducedor
, a new version of||
that has low precedence, for exactly this purpose.An example in Ruby where you could use
or
but not||
:If you used
||
, it would be a syntax error.I believe the idea is specifically to get them below the assignment operators, so you can write logic tests with assignments but without parens.
They have very low precedence so that the operands don't have to be wrapped in parentheses, as is sometimes the case with
&&
and||
.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.
The difference is precedence.
||
,&&
have higher precedence than=
, butand
,or
have lower. So while you can do:You would have to do:
to get same effect. If you do:
The result of expression would still be 0, but a value would be nil.