Mixing-in the inherited method


#1

Dear Rubyists,

I fail to understand why the following code doesn’t output anything.

module Foobar
def inherited(klass)
p klass
end
end

class Class
include Foobar
end

class A
end

My intuition says it should work since defining Class#inherited
directly works. I believe I understand the whole “instance methods of
Class become class methods of Class instances” business, but I must be
missing something obvious.

Any ideas?


#2

Christoffer S. wrote:

class Class

Any ideas?

A is not a subclass of Class, it’s an instance of Class.

Also, you need to use extend rather than include, so that the instance
methods of Foobar (particularly, #inherited) become methods of A.
Otherwise, the instance methods of Foobar become instance methods of
instances of A.

These two examples both print “A”:

module Foobar
def inherited(klass)
p klass
end
end

class Object
extend Foobar
end

class A
end


module Foobar
def inherited(klass)
p klass
end
end

class Classy
extend Foobar
end

class A < Classy
end


#3

Hello Joel,

A is not a subclass of Class, it’s an instance of Class.

Indeed.

Also, you need to use extend rather than include, so that the instance
methods of Foobar (particularly, #inherited) become methods of A.
Otherwise, the instance methods of Foobar become instance methods of
instances of A.

These two examples both print “A”:

/…/

I understand your examples and your argument, but you seem to be
missing my point (if I have one). Instance methods of class Class
become class methods of Class instances, so why doesn’t the mixed-in
inherited() work? Comparing these two examples, why is the output of
the second different?

= Example 1

class Class
def inherited(klass)
p klass
end

def test!
p “test!”
end
end

class A; end
A.test!

== Output

A
“test!”

= Example 2

module Foo
def inherited(klass)
p klass
end

def test!
p “test!”
end
end

class Class
include Foo
end

class A; end
A.test!

== Output

“test!”

Thanks,


#4

“C” == Christoffer S. removed_email_address@domain.invalid writes:

Try this

C> class Class

 remove_method :inherited

C> include Foo
C> end

Guy Decoux


#5

Guy Decoux wrote:

Try this

C> class Class

 remove_method :inherited

C> include Foo
C> end

Aha! That makes sense.

Thanks,