Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby Operators and Control Structures Logical Operators Practice time! Operators and Control Structures

alexandermason
alexandermason
713 Points

In the last video, it was explained that Ruby worked from right to left. On the answers 4 * 4 + 2 = 18 ? how-come?

Why in the answers is the math taken from left to right, when its taught on the video Ruby takes it from right to left which would leave the answer 24, and not 18 ? Curious?

2 Answers

Matthew Rigdon
Matthew Rigdon
8,223 Points

It isn't a sense of taking math from left to right or right to left. Which operation you perform first is based on order of operations, or PEMDAS:

  • P - parenthesis
  • E - exponents
  • M/D - multiplication/division (which ever appears first left/right)
  • A/S - addition/subtraction (which ever appears first left/right)

Examples:

4 * 4 + 2          =>   **(M/D is first)** 16 + 2 = 18
2 + 4 * 4          =>   **(M/D is still first)** 2 + 16 = 18

More advanced:

21 / 7 + 2 * 4                 =>  **(M/D is first, however there is both multiplication and division so which ever is first)**
3 + 2 * 4                        => **(M/D again)
3 + 8 = 11
alexandermason
alexandermason
713 Points

Thank you for such a clear explanation

alec