Lyndsy Simon

Development | Humor | Internet Marketing | Miscellany | Politics

Ruby's Inequality Operators

My annoyance of the day in Ruby: inconsistent usage of the inequality operator in the standard library.

The generic inequality operator in Ruby throws an exception when objects of differing types are compared. This, in my opinion, is a good thing. I don't want to accidentally attempt to compare an integer and a class, for instance.

1 < Class
# ArgumentError: comparison of Fixnum with Class failed

This makes sense!

Today, I discovered that the inequality operators are overridden for classes and modules to allow for checking inheritance:

class Foo; end
class Bar < Foo; end

Bar < Foo
# true

Foo < Bar
# false

Foo < Foo
# false

Foo <= Foo
# true

That's fine, I guess. It seems a little odd to consider something that is a subclass to be "less than" its ancestors, but I see the logic in it. Cool. Then I come across this:

1 < Class
# ArgumentError: comparison of Fixnum with Class failed

Class < 1
# TypeError: compared with non class/module

The overridden inequality operator for class and module comparison raises a different error class for a type mismatch than the generic implementation.


View comments.

All Posts

  1. | The ADD Developer
  2. | The Impact of Development Culture
  3. | Testing for the existence of a Flask request context
  4. | Reproducible Python Environments
  5. | Git Has Annoyed Me
  6. | Defining Gittip's Scope
  7. | The Future of Python is in the Past
  8. | Gittip Growth