Arithmetic Operators
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.
The shortcut
Before you trust a long expression, draw imaginary brackets around the highest-priority parts first: every **, then every *, / and %. Whatever is left is a simple chain of + and -.
The expression
total = 2 + 12 * 4.5 - 3 ** 2
If the bracketed version is not what you meant, write the real brackets into the code. They cost nothing and make your intention clear.
Drills
Answer fast — trust the rule.
What is 10 - 2 * 3?
What is 2 * 3 ** 2?
What is 24 / 4 * 2?
How do you add one to cups_sold in Ruby?
What does 4 + 2 really call?
Remember
- Powers first, then times and divide, then plus and minus; equal levels go left to right.
- Draw imaginary brackets from the highest priority down, or write real ones.
- Trap: no
++in Ruby, and integer division still drops the remainder.
