Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
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.
- Take
1 + 2 * 3
. If you didn't have order of operations, you'd assume that you add1
to2
, getting 3, and then multiply3 * 3
to get9
. But instead we get7
. - 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 get7
and not9
. The multiplication operator has higher precedence than the addition operator, so we do the multiplication first, giving us6
. We then add1
and6
, 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 + 2
is evaluated first, giving3
, and then that's multiplied by3
to give9
.
Helpful links:
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up