Search code examples
rubyinheritancemethodssuperderived

Calling Super Methods in Ruby


I am trying to define some classes in Ruby that have an inheritance hierarchy, but I want to use one of the methods in the base class in the derived class. The twist is that I don't want to call the exact method I'm in, I want to call a different one. The following doesn't work, but it's what I want to do (basically).

class A
    def foo
        puts 'A::foo'
    end
end

class B < A
    def foo
        puts 'B::foo'
    end
    def bar
        super.foo
    end
end

Solution

  • Probably, this is what you want?

    class A
      def foo
        puts 'A::foo'
      end
    end
    
    class B < A
      alias bar :foo
      def foo
        puts 'B::foo'
      end
    end
    
    B.new.foo # => B::foo
    B.new.bar # => A::foo