Question about right way to use module

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...:slight_smile:
Thanks.

Sam

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

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

(2) in your case

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

With (1) you can do

   include M
   f

not with (2)

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

  yes,

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?

  open a new scope

Guy Decoux