Comparisons in Ruby - a Proposal/Investigation

Author: Hugh Sasse <hgs@dmu.ac.uk>

Ruby is very good at expressing ideas clearly and concisely. It has unashamedly borrowed ideas from other languages, which eases the transition for new programmers.

One of the features of Ruby is the way that it handles booleans. Everything in Ruby is considered to be true, except for false and nil. This means that in Ruby:

    while(0)
        #...
    end

is an infinite loop. In C this would be a no-op.

This is only the second language I have encountered that regards zero as being true. The other language that had this property was Icon. Icon has some very nice features, although being goal directed in its execution it is rather difficult to get used to.

One of the featurs of Icon that is nice is that relational operators produce the right-hand-side when they are true. This means that 1 < 2 == 2 for example, but more than this it means that you can have longer expressions like 1 < x < 5. This is much how a mathematicion would tend to write such statements, and is much more readable than it would be in C:

    while((1 < x) && (x < 5))
    {
        ...
    };

For integers Ruby can do this using the Range type, of course, but it cannot use Floats in a range expression.

Suppose we were to change Ruby to allow this form of expression? I don't think much code would break. Existing code uses comparisons to yield a boolean. Where the boolean is tested, if it is true then the expression will still evaluate to true, unless it is nil. Where the comparison is false, a value of false will be produced as before, so that hehaviour shuld be unchanged.

The syntax rules certainly allow this form of expression. The only reason such ecpressions fail now is becuase FalseClass has no comparison methods, and because the right-hand-side is not returned by relational operators when the comparison is true.

I think such a change would lead to more readable code. So I have written a file compare_to_right2.rb which implements > and < methods which produce the right hand side on success. (I tried to write this as a module, but could not get it to work. See compare_to_right.rb for this attempt.) My icon_compare.rb shows that these can be used in expressions to good effect, in much the same way as they are in Icon.

I now invite the Ruby community to consider these ideas for future versions of the language.


Dave Thomas raised a good point about x == nil always failing. My reply quotes what he wrote.

See also Perl's RFC 25.


Created on 23-NOV-2000 by Hugh Sasse

Last Modified on 08-OCT-2001 by Hugh Sasse
$Revision$