module_function semantics

W

William Webber

Hi all!

I'm trying to understand some code in the stdlib (drb/drb.rb, to be
particular).

Is there any difference between:

module Foo

module_function
def bar()
"baz"
end

end

and

module Foo

def Foo.bar()
"baz"
end
end

?

Am I right in guessing that the former gives both a module and a mixin
function of the same name, whereas the latter gives on a module function?
Or are they in fact identical?

William
 
T

ts

W> module Foo

W> module_function

module_function make a private method and a public singleton method.

W> def bar()
W> "baz"
W> end

W> end

For example


svg% cat b.rb
#!/usr/bin/ruby
module A
def a
puts "a"
end
module_function :a

def self.b
puts "b"
end
end

A.a
A.b

include A
a
b
svg%

svg% b.rb
a
b
a
./b.rb:18: undefined local variable or method `b' for main:Object (NameError)
svg%


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

Staff online

Members online

Forum statistics

Threads
474,121
Messages
2,570,712
Members
47,282
Latest member
hopkins1988

Latest Threads

Top