Ruby Tutorial Ruby References

Ruby - Operators Precedence



Ruby Operators Precedence

Operator precedence (order of operations) is a collection of rules that reflect conventions about which procedures to perform first in order to evaluate a given expression.

For example, multiplication has higher precedence than addition. Thus, the expression 1 + 2 × 3 is interpreted to have the value 1 + (2 × 3) = 7, and not (1 + 2) × 3 = 9. When exponent is used in the expression, it has precedence over both addition and multiplication. Thus 3 + 52 = 28 and 3 × 52 = 75.

Operator Associativity

Operator associativity is the direction in which an expression is evaluated. For example:

x = 10
y = 20

#associativity of = operator is
#Left to Right, hence x will become 20
x = y

As the associativity of = is left to right. Hence x is assigned the value of y.

Example:

The example below illustrates the operator precedence in Ruby.

#evaluates 5 * 2 first
retval1 = 15 - 5 * 2

#above expression is equivalent to
retval2 = 15 - (5 * 2)

#forcing compiler to evaluate 15 - 5 first
retval3 = (15 - 5) * 2

puts "15 - 5 * 2 = #{retval1}"
puts "15 - (5 * 2) = #{retval2}"
puts "(15 - 5) * 2 = #{retval3}"

The output of the above code will be:

15 - 5 * 2 = 5
15 - (5 * 2) = 5
(15 - 5) * 2 = 20

Ruby Operators Precedence Table

The following table lists the precedence and associativity of Ruby operators. Operators are listed top to bottom, in descending precedence. Operators with higher precedence are evaluated before operators with relatively lower precedence.

PrecedenceOperatorDescription
21!Logical NOT
~Bitwise NOT
+aUnary plus
20**Exponential operator
19-aUnary minus
18*  /  %Multiplication, Division, Remainder
17+  -Addition, Subtraction
16<<  >>Bitwise left shift and right shift
15&Bitwise AND
14|Bitwise OR
^Bitwise XOR
13<  <=  >  >=Less than, Less than or equal, Greater than, and Greater than or equal
12==  !=Equality and Inequality
===  <=>Case equality, Combined Comparison Operator
=~  !~Pattern matching operators
11&&Logical AND
10||Logical OR
9..Range creation operators
...
8a?b:cternary (conditional) operator
7modifier-rescueException-handling modifier
6=Direct assignment
+=  -=  *=  /=  %=  **=Compound assignment by sum, difference, product, quotient, remainder and exponential
<<=  >>=Compound assignment by Bitwise left shift and right shift
&=  ^=  |=Compound assignment by Bitwise AND, XOR and OR
5defined?Test variable definition and type
4notLogical NOT
3andLogical AND
orLogical OR
2modifier-if  modifier-unless  modifier-while  modifier-untilConditional and loop modifiers
1{ }blocks

❮ Ruby - Operators