Skip to content

Operators

datanorris edited this page Jan 23, 2016 · 25 revisions

Class-defined operators

Unary operators

  • (unary minus)
  • (unary +) ~

! not

Binary arithmetic operators

& (binary & or formal block arg)

  • (binary minus) %
  • (binary *) ** / (binary /) ^ |
  • (binary +) << (left shift)

Match operators

=~ !~

Comparison operators

<

= <= <=> == != ===

Language-defined operators

Assignment

= mlhs/mrhs

Complex assignment

&&= ||=

|= %= &= **= *= ^= -= += /= <<=

=

Logical operators

&& || ? (ternary ?:) and or

defined?

defined?

Range constructors

Also for flipflops

.. ...

Operator precedence

Broadly, the following table describes the precedence of Ruby operators.

No|Type/Associativity|Description|Operators ---|---|---|---|--- 1|Binary left|Reference|. :: 2|Unary|General|! ~ + 3|Binary right|Power|** 4|Unary|Minus|- 5|Binary left|Products|* / % 6|Binary left|Additions|+ - 7|Binary left|Shifts|<< >> 8|Binary left|Bitwise and|& 9|Binary left|Bitwise or|| ^ 10|Binary left (TODO why?)|Directional comparisons|> >= < <= 11|Binary none|General comparisons|<=> == === != =~ !~ 12|Binary left|Logical and, argument form|&& 13|Binary left|Logical or, argument form||| 14|Binary left|Range constructors|.. ... 15|Ternary right|Logical ternary|?: 16|Unary|Defined|defined? 17|Binary none|Assignment modifier|rescue 18|Binary right|Assignments|= += -= etc. 19|Unary|Logical not, expression form|not 20|Binary left|Logical and/or, expression form|and or 21|Binary left|Statement modifiers|if unless while until rescue

Some special rules also apply:

  • If a rescue modifier is applied to an assignment, e.g. <lhs> = <rhs> rescue <value>, rescue becomes an assignment modifier and takes precedence over the assignment operator (i.e. it will be interpreted as <lhs> = ( <rhs> rescue <value> )) according to the following rules:
  • The assignment operator may be simple or complex
  • This does not apply to an assignment with a multiple left-hand-side, a multiple right-hand-side or a command call on the right-hand-side
  • If the argument to defined? or not? is within parentheses and there is no whitespace preceding it, then the operator has the highest precedence (higher even than . and ::)

Clone this wiki locally