How to Do Basic Math in Ruby
Ruby includes a large and powerful set of built-in capabilities. One of the most basic is the capability to do simple arithmetic. Enter 2 + 2 at the irb prompt and press Return (Enter):
2.2.2 :010 > 2 + 2 => 4
Wow, Ruby can do math you learned in kindergarten! Look at the other arithmetic operations of multiplication, division, and subtraction:
2.2.2 :011 > 10 * 5 => 50 2.2.2 :012 > 10 / 5 => 2 2.2.2 :013 > 10 - 5 => 5
Here, the symbols are a little different, but you get the results you’d expect. What if you want to try something even more complicated, like writing the math formula to convert degrees Fahrenheit to Celsius?
2.2.2 :018 > (212 - 32) * 5 / 9 => 100
You’re converting 212 degrees Fahrenheit by first subtracting 32, and then multiplying the result by 5 / 9. Ruby does the math and displays the result, 100 degrees Celsius, which is correct.
Why is the parentheses included in the formula? Try it again without them. Go ahead. Did Ruby still give you the right answer?
No, because Ruby, like some other programming languages, processes lines of code in a certain order. In the case of mathematics, as well as other operations it can do, Ruby has a sense of priorities in terms of what order it will run the code. The parentheses provide a programming hint to do the math in the order you want it to be done.
Without the parentheses, Ruby runs the formula in the order of doing multiplication and division before addition and subtraction, which is very different from what you want. It’s as if Ruby thought you said:
2.2.2 :020 > 212 - (32 * 5 / 9) => 195
Programmers call this prioritization order of operations or precedence, a fancy term, indeed. If you find that lines of code aren’t working the way you thought they would, check the precedence of the code you’re using.