+ 1
A confusion with precedence of operators(in ruby)
Can I get an explanation precedence of expression below? I was expecting a 0 but i'm getting 18 as output. Thank You :) x = 3*2*3+3/4%2*4/2%2 puts x
3 odpowiedzi
+ 1
Avinesh I don't think you are completely right in your first three lines of explanation. The precedence of the operators are in this format : +<-<%</<*<** from left to right.
Example : 5-2*3+3
The actual output to this series of operations will be 2 which can be only achieved if we follow the proper precedence order. Therefore - has more precedence than +
+ 2
+ and - operators have same precedence.
Similarly *, /, % have same precedence but the second set have higher precedence than + and - operator.
If there are operators with same precedence then we apply associativity which says that if there are operators with same precedence in an expression then they are executed from left to right.
In your case 3*2*3 = 18 then 3/4%2.... is executed which is 0. So 18 + 0 = 18.
+ 1
Owh okay. Thanks. I get it. I made a mistake while calculating the first mod operator.