Ruby Operator Precedence

From Techotopia

Purchase and download the PDF and ePub versions of this Ruby eBook for only $8.99

In the previous chapter of Ruby Essentials we looked at Ruby operators and expressions. An equally important area to understand is operator precedence. This is essentially the order in which the Ruby interpreter evaluates expressions comprising more than one operator.

Contents

When humans evaluate expressions, they usually do so starting at the left of the expression and working towards the right. For example, working from left to right we get a result of 300 from the following expression:

10 + 20 * 10 = 300

This is because we, as humans, add 10 to 20, resulting in 30 and then multiply that by 10 to arrive at 300. Ask Ruby to perform the same calculation and you get a very different answer:

irb(main):003:0> 10 + 20 * 10
=> 210

This is a direct result of operator precedence. Ruby has a set of rules that tell it in which order operators should be evaluated in an expression. Clearly, Ruby considers the multiplication operator (*) to be of a higher precedence than the addition (+) operator.