Instance_eval: why the class of subclass is superclass

Posted by Raj on Stack Overflow See other posts from Stack Overflow or by Raj
Published on 2010-05-03T13:53:45Z Indexed on 2010/05/23 14:10 UTC
Read the original article Hit count: 224

Filed under:
    def singleton_class
       class << self
         self
       end
    end

    class Human
      proc = lambda { puts 'proc says my class is ' + self.name.to_s }

      singleton_class.instance_eval do
        define_method(:lab)  do 
          proc.call
        end
      end
    end

    class Developer < Human
    end

    Human.lab # class is Human
    Developer.lab # class is Human ; oops

Following solution works.

def singleton_class
  class << self
    self
  end
end

class Human
  proc =  lambda { puts 'proc says my class is ' + self.name.to_s }
  singleton_class.instance_eval do
    define_method(:lab) do
      self.instance_eval &proc
    end
  end
end

class Developer < Human
end

Human.lab # class is Human
Developer.lab # class is Human ; oops

Why Developer.lab is reporting that it is Human ? And what can be done so that proc reports Developer when Developer.lab is invoked.

© Stack Overflow or respective owner

Related posts about ruby