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

Evaluates expr2 immediately after expr1 turns true.

expr1 ... expr2

Evaluates expr2 on the iteration after expr1 turns true.

In other contexts, they create a range object:

expr1 .. expr2

Includes both expressions (expr1 <= x <= expr2)

expr1 ... expr2

Doesn’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.

&& and

Returns true if both operands are true ...

Get Ruby in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.