From: Justin Collins Date: 2006-04-02T09:51:40+09:00 Subject: Re: Newbie! Programming Calculations Indifferent wrote: > Justin Collins wrote: >> Just like in math, the parentheses indicate what happens first. The >> inner-most parentheses are calculated first. >> >> An expression like: >> >> 98 + 59872 / 13 * 8 * -52 >> >> is evaluated as: >> >> 59872 / 13 = 4605 >> >> 4605 * 8 = 36840 >> >> 36840 * -52 = -1915680 >> >> -1915680 + 98 = -1915582 >> >> >> Compared to: >> >> 98 + (59872 / (13*8)) * -52 >> >> Which is evaluated as: >> >> 13 * 8 = 104 >> >> 59872 / 104 = 575 >> >> 575 * -52 = -29900 >> >> -29900 + 98 = -29802 >> >> >> The difference in order of evaluation is due to the parentheses. >> >> Hopefully that helps... >> >> -Justin > > > Cool thank you for the explanations guys :) > > One more thing: > In your example > 98 + (59872 / (13*8)) * -52 > > Why is -52 calculation done after the brackets are closed? > How come the +98 was done last? There is a thing (which other posts here mention) called operator precedence. Some operators come before others. If the operators have the same precedence, then it goes left to right. Here's an abbreviated precedence order for Ruby (from the Pickaxe, I can't find it online) from highest to lowest (first to last): ** (exponent) + - (unary plus and minus, positive and negative) * / % (multiplication, division, modulo) + - (addition, subtraction) So that's why -52 is 'negative fifty-two' and then it is multiplied. And why + 98 comes last. Some more general information here: http://en.wikipedia.org/wiki/Operator_precedence -Justin -- Posted via http://www.ruby-forum.com/.