Accessing functions in a module without 'include'

Usually I work with modules like this:

Defining a module in one file

module M
def f(x)

end
end

Using the module in another file

require ‘M’
include M
f(45)

Sometimes I would find it more convenient to not inject
the module’s namespace into the user’s namespace, i.e. to
do it without the include statement. I thought it would
be easy to qualify the foreign function with the module
name:

Using the module in another file

(this does not work)

require ‘M’
M::f(45) # Error: undefined method ‘f’

Maybe I’m thinking to Perlish here. Can it be done what I want
to achieve, and how?

Ronald

On Jun 29, 5:25 am, “Ronald F.” [email protected]
wrote:

Usually I work with modules like this:

Defining a module in one file

module M
module_function # <<<<<<<<< HERE
def f(x)

end
end

T.

Ronald F. wrote:

require ‘M’

(this does not work)

require ‘M’
M::f(45) # Error: undefined method ‘f’

Maybe I’m thinking to Perlish here. Can it be done what I want
to achieve, and how?

Not sure if it’s what you want, but if you define M as follows it works:

module M
def self.f(x)

end
end

cheers,
mick

end
Thank you, this works perfectly well!

Ronald

Defining a module in one file

module M
module_function # <<<<<<<<< HERE
def f(x)

end
end

Thank you, this is indeed one solution to my problem (though in the
end, I’m going to stick with Michael H.’ proposal).

Ronald

On Jul 2, 5:34 am, “Ronald F.” [email protected] wrote:

Defining a module in one file

module M
module_function # <<<<<<<<< HERE
def f(x)

end
end

Thank you, this is indeed one solution to my problem (though in the
end, I’m going to stick with Michael H.’ proposal).

Don’t mention it :slight_smile: BTW, Just to make sure you know, you can’t use
Micheal’s solution if you still want the option of including the
Module elsewhere. In effect using module_function is the same as:

module M
  def self.f(x)
    ....
  end
  def f(x)
    ....
  end
  private :f
end

Probably you’ve already figured that out, but just in case…

T.

  end
  private :f
end

I wasn’t aware that the instance functions would then go private,
but in my case this would be no problem anyway.

Ronald