Tuesday, October 11, 2011

Operators and precedence in Ruby

Now that we have established our most common data types, let's look at Ruby's operators. They are arranged here in order from highest to lowest precedence:

::
Scope
[]
Indexing
**
Exponentiation
+ - ! ~
Unary pos/neg, not, ....
* / %
Multiplication, division, ....
+ -
Addition/subtraction
<< >>
Logical shifts, ...
&
Bitwise and
| ^
Bitwise or, xor
> >= < <=
Comparison
== === <=> != =~ !~
Equality, inequality, ....
&&
Boolean and
||
Boolean or
.. ...
Range operators
= (also +=, -=, ...)
Assignment
?:
Ternary decision
not
Boolean negation
and or
Boolean and, or


Some of the preceding symbols serve more than one purpose; for example, the operator << is a bitwise left shift but is also an append operator (for arrays, strings, and so on) and a marker for a here-document. Likewise the + is for numeric addition as well as for string concatenation. As we shall see later, many of these operators are just shortcuts for method names.

No comments:

Post a Comment