Operator Expressions
Most operators are actually method calls. For example, a +
b is interpreted as a.+(b), where the
+ method in the object referred to by variable
a is called with b as its
argument.
For each operator (+ -
* / %
** & |
^ <<
>> &&
||), there is a corresponding form of abbreviated
assignment operator (+= -=
etc.)
Here are the operators shown in order of precedence (highest to
lowest):
:: |
[] |
** |
+(unary) -(unary) ! ~ |
* / % |
+ - |
<< >> |
& |
| ^ |
> >= < <= |
<=> == === != =~ !~ |
&& |
|| |
.. ... |
?: |
= (and abbreviated assignment operators such as +=, -=, etc.) |
not |
and or |
Nonmethod operators
The following operators aren’t methods and, therefore, can’t be redefined:
... |
! |
not |
&& |
and |
|| |
or |
:: |
= |
+=, -=, (and other abbreviated assignment operators) |
? : (ternary operator) |
Range operators
Range operators function differently
depending on whether or not they appear in conditionals,
if expressions, and while
loops.
In
conditionals, they return true from the point
right operand is true until left operand is
true:
expr1..expr2Evaluates
expr2immediately afterexpr1turnstrue.expr1...expr2Evaluates
expr2on the iteration afterexpr1turnstrue.
In other contexts, they create a range object:
expr1..expr2Includes both expressions (
expr1<=x<=expr2)expr1...expr2Doesn’t include the last expression (
expr1<=x<expr2)
Logical operators
If the value of the entire expression can be determined with the value of the left operand alone, the right operand isn’t evaluated.
&& andReturns
trueif both operands aretrue ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access