Philpot
Philpot

Reputation: 246

Ruby modulus. Why are these two sums printing different answers?

I'm learning ruby and having problems with the %Modulus sums.

puts "example #{101 % 4}"

The above prints 1 in the terminal which is what I expected.

Why does the below print 101 in the terminal? Surely it's the same as above?

puts "example #{100 + 1 % 4}"

I understand that % is just another way of saying 'X divided by Y with J remaining". Therefore surely the 2nd example should also return 1?

Any help will be greatly appreciated.

Upvotes: 0

Views: 80

Answers (3)

Sagar Pandya
Sagar Pandya

Reputation: 9497

As pointed out it's to do with operator precedence, which you can control using parentheses () for example. The rules for Ruby are outlined in the official Ruby documentation as follows:

From highest to lowest, this is the precedence table for ruby. High precedence operations happen before low precedence operations.

!, ~, unary +

**

unary -

*, /, %

+, -

<<, >>

&

|, ^

>, >=, <, <=

<=>, ==, ===, !=, =~, !~

&&

||

.., ...

?, :

modifier-rescue

=, +=, -=, etc.

defined?

not

or, and

modifier-if, modifier-unless, modifier-while, modifier-until

{ } blocks

For a more general overview of order or precedence (outside the scope of programming) see the wikipedia entry here.

What happens if there's a tie?

It's worth noting that if there's a tie (i.e. two operators of the same precedence are in your calculation) then the operations are carried out from left to right.

Consider:

10 % 3 * 4
#=> 4 
10 * 3 % 4
#=> 2 

or

10 * 10 / 2 * 4
#=> 200 
10 / 10 * 2 * 4
#=> 8

Upvotes: 2

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230286

Parentheses are important. Because of operator precedence rules, the second example is seen by ruby as

100 + (1 % 4)

Which gives

100 + 1

which equals 101

You probably meant

(100 + 1) % 4

Upvotes: 5

Ursus
Ursus

Reputation: 30056

Because % has an higher precedence than +. So you could do something like

puts "example #{(100 + 1) % 4}"

Upvotes: 3

Related Questions