module_function and Object include.

K

Kedar Mhaswade

I understand that the use of the Module's class method "module_function"
is to
- create class method copies of the instance methods defined in module
- make those instance methods "private" when mixed in.

e.g.
1 module Functions
2 module_function
3 def greet(whom)
4 puts "Hi, #{whom}"
5 end
6 end

Now, if I included this module in my class like:
class Greeter
include Functions
end

everything works as expected.

But, if I opened up the Object class and included Function there e.g.
class Object
include Functions
end
(like probably what Ruby does with Kernel module),

then I find that module_function (line #2 above) is __not__ needed!

Do I conclude that including a module in Object class has the same
effect as module_function?

Thank you,
Kedar
 
S

Su Zhang

"Including a module in Object class" simply makes every object respond
to the mixed-in methods.

In your case, `greet' is made available as an instance method of Object.
The class `Greeter' is derived directly from `Object', thus also
inherits the instance method 'greet'. Furthermore, the class `Greeter'
itself is an object of type `Class', which inherits from `Object' too,
so 'Greeter' itself (without the presence of any instance of it) also
responds to 'greet'.
 
K

Kedar Mhaswade

This is different from making it a module function and including it only
within `Greeter', for which only instances of type 'Greeter' and its
subclasses as well as the class `Greeter' itself respond to 'greet'.

Thanks! You are right.

Thus, in order to make my "functions" available as pure functions to all
my "classes" and instances (e.g. like Kernel.puts), it suffices to open
up Object and include my Functions module in it (without requiring
module_function called in my module).
 

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

No members online now.

Forum statistics

Threads
473,968
Messages
2,570,153
Members
46,699
Latest member
AnneRosen

Latest Threads

Top