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?
···
--
Christoffer Sawicki
Christoffer Sawicki wrote:
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?
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
--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407
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,
···
--
Christoffer Sawicki