What do they do? What are the brackets for?
I sort of remember doing something simular to this when I was using
excel in a course i did. Is the number is the brackets calculated first?
Can someone explain this to me? Or give me a link were I can find more
Extreamly confused newbie! Please help!
When you have an expression that uses more than one arithmetic operator,
such as 6 + 12 / 3, it’s not always obvious which operations should be
performed first. Should we add 6 and 12 first, or divide 12 by 3 and
then add 6?
Ruby follows a couple of very simple rules in this case.
Rule 1: First do all the multiplications and divisions, then all the
additions and subtractions.
Rule 2: If there are more than 1 multiplication or division, or more
than one addition or subtraction, do them from left to right.
So, for 6 + 12 / 3, Ruby divides 12 by 3 first, which gives it 4, and
then adds 6 and 4, so the result is 10.
Now it’s possible that you may want Ruby to actually add 6 and 12 and
then divide the result by 3, so Ruby gives you a way to tell it to do it
that way. To do this, enclose 6 + 12 in parentheses: (6 + 12) / 3. Ruby
will do the addition, getting 18, and then divide 18 / 3, giving 6.
You can nest the parentheses, in which case the most deeply nested
expressions are evaluated first: ((3+5)/2)+6 means “add 3 and 5, divide
by 2, and add 6”.
For rule 2, given the expression 24 / 2 * 3, since division and
multiplication are equally “important,” Ruby just goes left to right.
First it divides 24 / 2, giving 12, then multiplies by 3, giving 36.
Similarly, for 12 + 3 - 5, Ruby adds 12 and 3, giving 15, and then
subtracts 5, giving 10.
Regarding -15, or -52, consider that most arithmetic operations are
“binary,” that is, the operation produces a result by combining two
numbers. However, we can say that a number is negative by preceding it
with a minus sign. The minus sign is called a “unary” operator. That is,
it produces its result from only one number.
Since a unary minus sign negates the number it precedes, 25 + =15 adds a
negative 15 to 25, which is the same as subtracting 15 from 25.