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.

Ugh.

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. | An Open Letter to Target
  5. | Reproducible Python Environments
  6. | Reinventing the "Save" Icon
  7. | PyCon Drama
  8. | Oh yeah...
  9. | Git Has Annoyed Me
  10. | The Security of a Free State
  11. | For War, D
  12. | Defining Gittip's Scope
  13. | The Future of Python is in the Past
  14. | Gittip Growth
  15. | Personal Renewal
  16. | It’s Not About Just Having A Cool Ad…
  17. | Get Around the “Main Street Fairness Act” – and Get Your Amazon Affiliate Account Back