0
class Base
  def sam
    "I m the base"
  end

  def self.inherited(base)
    alias_method :old_sam, :sam
    base.class_eval do
      def sam
        old_sam 
        p "Inside inherited"
      end
    end
    super
  end
end

class Derived < Base
  def sam
   p "Inside Derived"
  end
end

when Derived.new.sam => "Inside Derived"

But I expect

"Inside Derived"

"Inside inherited"

New to ruby. Any help will be greatly appreciated.

Subin
  • 33
  • 4

1 Answers1

0

You have simply overriden the defined by base.class_eval method sam in Derived.

If you remove the method sam from Derived:

class Derived < Base
end

You will get:

#=> "Inside inherited"
#=> ArgumentError: wrong number of arguments (given 1, expected 0)

The latter is because you are passing an argument to old_sam method, which does not take it:

old_sam p "Inside inherited"

But I expect

"Inside Derived"

"Inside inherited"

This is not possible with your set up, because what you do is first defining an instance method sam in class_eval block for all descending classes, but later just overriding in.

Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
  • Thanks Andrey. The method old_sam doesn't accept any arguments, and the code is changed accordingly now. Sorry for that. – Subin Feb 03 '17 at 11:11
  • @Raj I answered your question, editing it down the way not a good choice and it does not make sense now since it does not change the answer given. – Andrey Deineko Feb 03 '17 at 11:39