Modules & include

Why do I get an exception? Shouldn’t Mod2 have the method return_true
because it included Mod1?

irb(main):001:0> module Mod1
irb(main):002:1> def return_true
irb(main):003:2> true
irb(main):004:2> end
irb(main):005:1> end
=> nil
irb(main):006:0> module Mod2
irb(main):007:1> include Mod1
irb(main):008:1> def self.test
irb(main):009:2> return_true
irb(main):010:2> end
irb(main):011:1> end
=> nil
irb(main):012:0> Mod2.test
NameError: undefined local variable or method `return_true’ for Mod2:Module

Why do I get an exception? Shouldn’t Mod2 have the method return_true
because it included Mod1?

irb(main):001:0> module Mod1
irb(main):002:1> def return_true
irb(main):003:2> true
irb(main):004:2> end
irb(main):005:1> end
=> nil
irb(main):006:0> module Mod2
irb(main):007:1> include Mod1
irb(main):008:1> def self.test
irb(main):009:2> return_true
irb(main):010:2> end
irb(main):011:1> end
=> nil
irb(main):012:0> Mod2.test
NameError: undefined local variable or method `return_true’ for
Mod2:Module

Mod2 itself does not have that method; if you had defined return_true
as ‘self.return_true’ then it would have worked. Or you could have
called ‘module_method :return_true’, I think. Otherwise, those methods
get added as instance methods. You can mix them into a class:

module Mod1
def return_true
true
end
end
=> nil
module Mod2
include Mod1
def test
return_true
end
end
=> nil
Mod2.test
NoMethodError: private method `test’ called for Mod2:Module
from (irb):111
class Klass
include Mod2
end
=> Klass
Klass.new.test
=> true

cheers,
–Mark

···

On Apr 23, 2004, at 11:34 AM, Andreas Schwarz wrote:

Why do I get an exception? Shouldn’t Mod2 have the method return_true
because it included Mod1?

irb(main):001:0> module Mod1
irb(main):002:1> def return_true
irb(main):003:2> true
irb(main):004:2> end
irb(main):005:1> end
=> nil
irb(main):006:0> module Mod2
irb(main):007:1> include Mod1

···

On Sat, Apr 24, 2004 at 03:34:08AM +0900, Andreas Schwarz wrote:
=======
extend

irb(main):008:1> def self.test
=========
if this were def test, include Mod1 would do what you want (or the
other way around, you’d want what include Mod1 does :wink:
irb(main):009:2> return_true
irb(main):010:2> end
irb(main):011:1> end
=> nil
irb(main):012:0> Mod2.test
NameError: undefined local variable or method `return_true’ for Mod2:Module


Running Debian GNU/Linux Sid (unstable)
batsman dot geo at yahoo dot com

LILO, you’ve got me on my knees!
– David Black, dblack@pilot.njin.net, with apologies to Derek and the
Dominos, and Werner Almsberger