Simple metaclass question

B

bob zee

Code 1:
-------
module Mod
def hello
"Hello from Mod.\n"
end
end
class Klass
def hello
"Hello from Klass.\n"
end
end

k = Klass.new
p k.hello #=> "Hello from Klass.\n"
k.extend(Mod)
p k.hello #=> "Hello from Mod.\n"

Code 2:
--------
module Mod
def hello
"Hello from Mod.\n"
end
end
class Klass
include Mod
def hello
"Hello from Klass.\n"
end
end
k = Klass.new
p k.hello #=> "Hello from Klass.\n"
k.extend(Mod)
p k.hello #=> "Hello from Klass.\n"

Why last k.hello is "Hello from Klass" Not "Hello from Mod"? After
Klass mixin with Mod, I am extending k object to include Mod so k's
metaclass methods now point to Mod methods.. right? they should get
called first before Klass instance methods if I am thinking right.
 
G

Giles Bowkett

IIRC, the reason it doesn't work the way you expected is that adding a
mixin gives you a new point on a tree. Ruby searches the tree for
methods. If you tell it to go to the method hello, it finds that right
away, right there in the class, so it never bothers to check further
up the tree. It looks first in the class, and then in the module.

--
Giles Bowkett

Blog: http://gilesbowkett.blogspot.com
Portfolio: http://www.gilesgoatboy.org
Tumblelog: http://giles.tumblr.com/
 
M

MenTaLguY

Why last k.hello is "Hello from Klass" Not "Hello from Mod"? After
Klass mixin with Mod, I am extending k object to include Mod so k's
metaclass methods now point to Mod methods.. right? they should get
called first before Klass instance methods if I am thinking right.

Ruby inheritance is linearized so that each module only appears once.
Since Mod is already present in k's class ancestry, adding it again
has no effect.

-mental
 
B

bob zee

Giles said:
IIRC, the reason it doesn't work the way you expected is that adding a
mixin gives you a new point on a tree. Ruby searches the tree for
methods. If you tell it to go to the method hello, it finds that right
away, right there in the class, so it never bothers to check further
up the tree. It looks first in the class, and then in the module.

--
Giles Bowkett

Blog: http://gilesbowkett.blogspot.com
Portfolio: http://www.gilesgoatboy.org
Tumblelog: http://giles.tumblr.com/

Giles ...I think Search path is like this Singleton Object then any
modules mixin by singleton object then the Class then Mixed Modules
then Super classes. But as I am mixin same Module for singleton object
which is mixin by Class already, it is skipping it as Rick and mental
points out.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,149
Members
46,695
Latest member
StanleyDri

Latest Threads

Top