Modules & include

A

Andreas Schwarz

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
 
M

Mark Hubbart

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:
NoMethodError: private method `test' called for Mod2:Module
from (irb):111=> true

cheers,
--Mark
 
M

Mauricio Fernández

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 =======
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 ;)
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, (e-mail address removed), with apologies to Derek and the
Dominos, and Werner Almsberger
 

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

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,140
Latest member
SweetcalmCBDreview
Top