Arithmetic Operators
Ruby evaluates powers first, then multiplication, division and remainder, then addition and subtraction, and every operator is really a method on the left-hand object.
Track operand types and evaluation order through a calculation.
Bean Cart's closing report needs a total: 12 lattes at 4.50, plus 5% tax. That is a one-line calculation, but only if you know exactly how Ruby orders the steps and what each operator does with integers versus floats.
The rule
Powers first, then times and divide, then plus and minus.
Ruby's arithmetic operators:
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ |
add | 4 + 2 |
6 |
- |
subtract | 4 - 2 |
2 |
* |
multiply | 4 * 2 |
8 |
/ |
divide | 9 / 2 |
4 |
% |
remainder (modulo) | 9 % 2 |
1 |
** |
power | 2 ** 3 |
8 |
The order of operations follows school maths. ** binds tightest, then *, / and % (worked left to right), then + and - (left to right). Parentheses override everything.
2 + 3 * 4 # => 14, not 20
(2 + 3) * 4 # => 20
2 * 3 ** 2 # => 18, because 3 ** 2 happens first
20 / 4 * 2 # => 10, left to right: 5 * 2
12 * 4.50 * 1.05 # => 56.7 (roughly; floats are approximate)Two things are special to Ruby. First, the integer-versus-float rule from the data types section still applies: 9 / 2 is 4, and 9 / 2.0 is 4.5. Second, these operators are really methods. 4 + 2 is friendly shorthand for 4.+(2). That is why "ab" + "cd" joins strings and [1] + [2] joins arrays: each class defines its own +.
There is no ++ or -- in Ruby. To add one, write cups_sold += 1.
Dividing an integer by zero raises ZeroDivisionError. Dividing a float by zero does not: 1.0 / 0 gives Infinity.