+ 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

6th Apr 2020, 9:02 AM
Anurag Mondal
Anurag Mondal - avatar
3 Antworten
+ 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 +
6th Apr 2020, 9:41 AM
Anurag Mondal
Anurag Mondal - avatar
+ 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.
6th Apr 2020, 9:12 AM
Avinesh
Avinesh - avatar
+ 1
Owh okay. Thanks. I get it. I made a mistake while calculating the first mod operator.
6th Apr 2020, 9:31 AM
Anurag Mondal
Anurag Mondal - avatar