Search code examples
rubymethodsextending

Problem with accessing superclass methods in method redefinitions


I am having a bit trouble to understand when "super" can be called and when not. In the below example the super method leads to a no superclass error.

class Bacterium
  def eats
    puts "Nam"
  end
end

class Bacterium
  def eats
    super # -> no superclass error
    puts "Yam"
  end
end

b = Bacterium.new
b.eats

But this works:

class Fixnum
  def times
    super # -> works
    puts "done"
  end
end

5.times { |i| puts i.to_s }

Is 5 not just also an instance of Fixnum. And am I not redefining an existing method like in the Bacterium example above?


Solution

  • No, not really. Fixnum inherits from Integer class, and you are in fact overriding Integer#times, so super works, as it calls implementation from the parent.

    In order to achieve something similar when monkeypatching, you should alias method before redefining it, and there call it by alias.

    class Bacterium
      alias_method :eats_original, :eats
      def eats
        eats_original # -> "Nam"
        puts "Yam"
      end
    end
    

    Class reopening is not a form of inheritance and super is of no use there.