rubyinheritanceruby-comparable

How can Ruby `Complex` class have `Comparable` in its ancestors when it has none of its relational operator except `==`?


Indeed:

Comparable.instance_methods # => [:clamp, :<=, :>=, :==, :<, :>, :between?]
Complex.ancestors # => [Complex, Numeric, Comparable, Object, PP::ObjectMixin, Kernel, BasicObject]
Complex.instance_methods.select{Comparable.instance_methods.include? _1} # => [:==]

Of course, == is also defined in BasicObject, so even == doesn't count that much.

How is that possible? Can you remove an ancestor method in Ruby?

Is it possible to remove methods at all?


Solution

  • You can remove a method in two ways, undef_method and remove_method

    undef_method will remove the ability to call the method competely, but remove_method will remove just the current method, letting you fall back to the super method if it exists.

    class Foo
      undef_method :bar
    end