Ahh, the Subtleties of Ruby's Operator Precedence
Posted by Rick DeNatale Tue, 07 Aug 2007 19:24:00 GMT
Not long ago while working on an existing Rails application, (i.e. code I hadn’t written). I was mystified when a logical expression seemed to be returning an odd result. The expression had been written with not, and, and or, and was the right hand side of an assignment statement. ventually I changed to using !, &&, and || which fixed the problem. I never completely understood what was going on, until I encountered this blog entry by Jay Fields.
One of the big differences between Ruby and Smalltalk is the use of operator precedence. In Smalltalk, the grammar is very simple, unary message selectors bind tighter than binary selectors, which bind tighter than keyword selectors. The assignment operator binds more loosely than any of these. This is often a stumbling block for newcomers to Smalltalk when they find that in Smalltalk 3 + 5 * 2 evaluates to 16.
Ruby in comparison has quite a rich and flexible syntax. Usually, it’s quite intutitive, but, depending on where you come from there can be some surprises.
I understood the relative precendences of, say && vs. and in Ruby, but the fact that and had weaker precedence than = escaped me, until Jay’s article turned the light on for me.
As they say, you learn something new everyday, or at least you hope you do. I don’t expect that I’ll forget this little corner of Ruby in future









