Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Start a free Basic trial
to watch this video
Ruby follows the same conventions as math! That means that operators have precedence over other operators and follow the order of operations.
Ruby Operator Precedence
( ) # Parentheses
! # Not
** # Exponentiation
% / * # Modulus, Division, Multiplication
+  # Addition and Subtraction

0:00
When we have multiple operators on the same line of code,

0:03
the order in which things are evaluated can change

0:06
depending on how important the operators are to Ruby.

0:11
This is just like regular math where parentheses are evaluated first,

0:15
then exponents, multiplication and division, then addition and subtraction.

0:21
We group statements the same way in Ruby using parentheses.

0:25
After that, the different operators have different levels of precedents.

0:30
This gives us a lot of power when writing Ruby programs.

0:34
Let's see how that works now using Workspaces.

0:38
Okay. So I have just launched a new

0:40
Ruby workspace.

0:42
And, we're gonna do our work in IRB here.

0:45
So I'm gonna drag that up, and in the consult area type irb, and press Enter.

0:52
Now let's go ahead and just see how some of these operators work.

0:57
When we type them all out on the same line,

1:00
let's see how Ruby interprets what's happening.

1:03
So if I were to do 1 plus 1, it would be 2, but

1:09
if I do 1 plus 1 and then I do times 2, it's 3.

1:14
Now if it were just going left to right, we would expect that to be 2 times 2.

1:22
But, actually, Ruby is interpreting 1 times 2 first,

1:27
and then adding 1 to that, so that becomes 3.

1:31
Now, if instead of [SOUND] multiplication,

1:35
[SOUND] we did subtraction, that all works the same way.

1:41
So lets see, 1 plus 1 minus 5, [SOUND] that becomes negative 3.

1:48
So that would be 2 minus 5.

1:49
You know if we wanted to we could change this.

1:53
So let's say we had 10 and

1:56
we wanted to subtract [SOUND] 10 and 1,

2:01
we could just surround it with parentheses and

2:06
that would make this part more important.

2:11
And you can do that any number of times,

2:16
so if we said 2 times 2, times 4.

2:20
[SOUND] Looks like Workspaces got a little funny there.

2:27
Let's try that again.

2:28
2 times 2, times 4 is 16.

2:33
[SOUND] And we can do that, minus 6.

2:39
[SOUND] Now multiplication and division, and modulus have the same precedence.

2:46
After that is addition and subtraction.

2:51
[SOUND] And clear my screen here, and

2:56
we'll do 10 modulus 5 is 0,

3:00
[SOUND] plus 1 [SOUND] is 1.

3:04
So we can see that the modulus here has more precedence than the plus.
You need to sign up for Treehouse in order to download course files.
Sign up