Operator Precedence2:12 with Jay McGavren
You can chain math operations together. But sometimes the order you carry those operations out affects the final result. Let's look at the rules surrounding the order of operations.
- You can chain operations together:
1 + 2 + 3
- Order of operations you were taught in math class applies in Ruby too.
1 + 2 * 3. If you didn't have order of operations, you'd assume that you add
2, getting 3, and then multiply
3 * 3to get
9. But instead we get
- This is because of order of operations. In chained math operations, multiplication and division operations always come first, and addition and subtraction second:
* / + -
- Ruby respects this concept by following something called operator precedence. That is, the evaluation of some operators precedes the evaluation of some other operators. The multiplication and division operators have higher precedence than addition and subtraction operators.
- So that's why when we evaluate
1 + 2 * 3, we get
9. The multiplication operator has higher precedence than the addition operator, so we do the multiplication first, giving us
6. We then add
6, giving us 7.
- Suppose we wanted to ensure that the addition operation occurs first. If we were working in a math textbook, we'd add parentheses around the operation to indicate it should go first, no matter what:
(1 + 2) * 3.
- And that same notation works in Ruby. Ruby will always evaluate math operations within parentheses first, before it goes on to evaluate the rest of the expression. So with the parentheses,
1 + 2is evaluated first, giving
3, and then that's multiplied by
You need to sign up for Treehouse in order to download course files.Sign up