Question about right way to use module

S

Sam Sungshik Kong

Hi, folks!

Modules are used for
1. mixins
2. function containers

I want to make some utility functions in a module which will be mostly used
in irb to test things.
The module won't be used for a mixin, only for a function container.

Q1) Which of the following two is the better way for the purpose(function
container)?

(1)
module M
module_function
def f
...
end
end

(2)
module M
def self.f
...
end
end

If I understand correctly, (1) copies the function and wastes space. Then
(2) will serve my purpose better. Am I correct?

Q2) In the above, is (1) exactly same as the following?

module M
def f
...
end
module_function :f
end

Q3) If I do (1), how can I end module_function section? One way I can think
of is close the module and re-open it. Any other way?
module M
module_function
def f
...
end
def f2 #->still module_function
...
end
def f3 #I want to make f3 non-module_function
...
end
end

Q4) Let's say that I created functions in a deeply nested module, is there a
short-cut to call the function besides 'include module'?

M1::M2::M3.f
I wish I could make an alias like
alias :M :M1::M2::M3 #wrong example
M.f

I guess I asked too many questions for this late night...:)
Thanks.

Sam
 
G

Gavin Sinclair

Sam wrote (edited):
[I want to write a module, which] won't be used for a mixin, only
for a function container.

Q1) Which of the following two is the better way for the
purpose: 'module_function' or 'def self.method'?

Personally, I find 'module_function' unintuitive, so I stick with 'self'.
There's another idiom I sometimes employ:

module X
def f
end
extend self
end

X.f # -> nil, which is better than "error"

I don't know the answer to Q2 or Q3, so they're snipped.
Q4) Let's say that I created functions in a deeply nested module, is
there a short-cut to call the function besides 'include module'?

That's easy!

module M1::M2::M3::M4 # Only works if M1-3 already exist.
def self.foo; 5; end
end

M4 = M1::M2::M3::M4 # Here's your shortcut.

M4.foo # -> 5


Cheers,
Gavin
 
T

ts

S> Q1) Which of the following two is the better way for the purpose(function
S> container)?

(2) in your case

S> If I understand correctly, (1) copies the function and wastes space. Then
S> (2) will serve my purpose better. Am I correct?

With (1) you can do

include M
f

not with (2)

S> Q2) In the above, is (1) exactly same as the following?

yes,

S> Q3) If I do (1), how can I end module_function section? One way I can think
S> of is close the module and re-open it. Any other way?

open a new scope



Guy Decoux
 

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,774
Messages
2,569,596
Members
45,142
Latest member
DewittMill
Top