Module_function question


#1

Hi to everyone,

let’s say I’ve the following astonishing module:


module Mod # contained in the file “mymodule.rb”
CONST = 1974

def initialize()
@initialized_value=892
end

def metodo1()
puts “this is metodo1”
end

class MyModClass
attr_reader :mymodclass_value
def initialize()
@mymodclass_value = 2005
end
end

module_function :metodo1

end

is it correct that “module_function :metodo1” should allow me to access
to “metodo1” the following ways:


require ‘mymodule’

Mod.metodo1() # This is Ok, and works as expected

class MyClass
include Mod
attr_reader :myclass_value
attr_reader :initialized_value
def initialize()
super()
@myclass_value = Mod::CONST
end
end

temp = MyClass.new()

temp.metodo1() # without the module_function, this works!

Why the line “temp.metodo1()” gives the error:
“Private method ‘metodo1’ called for…” ?

The Pickaxe book states that using “Module#module_function” actually
makes a copy of the methods and not an alias.

Thanks again for your help.
Regards,
Carmine


#2

“C” == Carmine M. removed_email_address@domain.invalid writes:

C> Why the line “temp.metodo1()” gives the error:
C> “Private method ‘metodo1’ called for…” ?

module_function make the method private (i.e. a method which can’t be
called with a receiver) and create a public method for the singleton
class

C> The Pickaxe book states that using “Module#module_function” actually
C> makes a copy of the methods and not an alias.

The book is trying to say this

module Mod
def meth
puts “meth”
end

  module_function :meth

  def meth
     puts "new_meth"
  end

end

include Mod

Mod.meth # meth
meth # new_meth

if module_function just created an alias, the 2 calls will give the
same
output

Guy Decoux


#3

Hi Guy,
Clear now.

I do promise I’ll stop bothering with silly questions unless tomorrow :wink:

Regards,
Carmine


#4

Selon Carmine M. removed_email_address@domain.invalid:

Hi Guy,
Clear now.

I do promise I’ll stop bothering with silly questions unless tomorrow :wink:

Don’t worry, people don’t mind silly questions here, as long as they are
on-topic :wink: .

Christophe G…

http://rainbow.conlang.free.fr

It takes a straight mind to create a twisted conlang.