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

Posted in , ,  | Tags ,  | 1 comment | 1 trackback

Comments

  1. Daniel Berger said about 15 hours later:

    I don’t think I’ve ever used ‘and’, ‘or’ or ‘not’, and I doubt I ever will precisely because it’s too easy to get yourself into trouble with precedence.

Trackbacks

Use the following link to trackback from your own site:
http://talklikeaduck.denhaven2.com/articles/trackback/452

  1. From The Rubylution
    Ruby's Operator Precedence: More subtle than you might think
    I just read Rick DeNatale's article about Ruby's Operator Precedece, in which he mentioned, that Ruby's and and or operators have a weaker precedence than && and || (and also weaker than =). This is similar to Perl's and and or operators, ...

Comments are disabled