Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby Basics Numbers Operator Precedence

Eudes Lima
Eudes Lima
4,046 Points

Operator precedente question

I'm in doubt... operators aren't methods themselves? The expression "1 + 2 * 3" returns 7. But, "1.+(2).*(3)" returns 9. So this last expression doesn't follow operator precedence. What I'm missing?

3 Answers

Andres Martinez
Andres Martinez
2,034 Points

When you enclose a number in "( )" you are creating precedence for that number. The program in this situation starts with the 2 first and ignores the three because it will take precedence next since it is the next enclosed number in "( )". It will add 1 to 2 and then what's left is to multiply to 3. For example "1. +(2)*3" will also equal 9.

Eudes Lima
Eudes Lima
4,046 Points

But, considering "1.+(2).*(3)", if the parenthesis makes the precedence, why do the number 1 is considered first before the number 3 that is in parenthesis? With 2 and 3 in parenthesis, it should multiply them before sum with 1. Don't you think? I think that this rational is different in some way...

Andres Martinez
Andres Martinez
2,034 Points

I believe it is because the "1." in combination with putting individual integers in ( ) its almost like you are deliberately trying to hide parts of the equation. Any numbers after the 1. can be interpreted by the program as part of the 1.float therefore giving "1." similar precedence. For example 1.-(2)+(3) will = 2 and !=4 . 1.-2 = -1 then .-1+3= 2.. And 1.-(2)*(3) will = -3 and !=5. For some reason ruby seems to give precedence to "1.". I would not use "( )" on individual numbers without good reason. because * / already have precedence without "( )" don't confuse yourself and the program lol

Eudes Lima
Eudes Lima
4,046 Points

Hello! Sorry for the late response. I understand that writing 1.+(2).*(3), and its variations, is very confusing. I definitely would not use it that way. I'm just trying to understand how Ruby would handle these statements. I have read a little, and saw that before the code goes to the interpreter it is first parsed to create the AST. That said, turns out that it is very clear that depending of how we write the expressions it could create the AST with a different precedence, with a different order of method call. So, 1 + 2 * 3 is parsed as (+ (* 3 2) 1), and 1.+(2).*(3) is parsed as (* (+ 1 2) 3), resulting in the values that we have saw. :)