Philpot - 11 months ago 64

Ruby Question

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.

Answer Source

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
```