See code samples below. Notes:
- the def test defines a private method in Object. This means that every
object can call it on itself. - Defining the method means overriding the previous definition. From
within the method you can access ‘super’, but not from without. - Module names should begin with capital letters.
- Modules cannot be instantiated directly (only though a class), so you
cannot access the superclass.test method (there simply isn’t a
superclass).
HTH,
— CODE —
def test
p “in first test”
end
module Somemodule
def Somemodule::somemethod
TOPLEVEL_BINDING.send(:test)
# ugly hacks that also work:
Object.new.send(:test)
eval("test", TOPLEVEL_BINDING)
end
def Somemodule::test(call_super)
p “in somemodule::test”
# another option:
p super if call_super
end
end
Somemodule.somemethod
···
-----Original Message-----
From: Sean O’Dell [mailto:sean@celsoft.com]
Sent: Friday, 28 May 2004 10:24 AM
To: ruby-talk ML
Subject: Re: Calling global method
On Thursday 27 May 2004 16:37, Sean O’Dell wrote:
How do you call a global method from a module method where there is
another
module method that shares the name of the global method?
Perhaps that was too cryptic. Here’s an example:
def test
p “in first test”
end
module somemodule
def somemodule::somemethod
test()
end
def somemodule::test
p “in somemodule::test”
end
end
In somemodule::somemethod, I intended to call the global test method,
but I
ended up calling somemodule::test.
How do you call the outer global method in a case like this?
Sean O'Dell