usage of Module.new

S

Schüle Daniel

Hello,

one can generate modules with

m = Module.new

m.module_eval do
def self.a;"a";end
def b;"b";end
end

but how can I 'include' them in a class

class A
include m # this doesn't work
end

is it possible?

Regards, Daniel
 
D

Daniel Schierbeck

Schüle Daniel said:
one can generate modules with

m = Module.new

m.module_eval do
def self.a;"a";end
def b;"b";end
end

but how can I 'include' them in a class

class A
include m # this doesn't work
end

As Tim said, you can assign the module to a constant. This isn't because
#include only accepts modules (that wouldn't even be possible, I think),
but rather it's a scoping issue.

class A
m = Module.new{define_method:)foo){"bar"}}
include m
end

Cheers,
Daniel
 
S

Schüle Daniel

[...]
As Tim said, you can assign the module to a constant. This isn't because
#include only accepts modules (that wouldn't even be possible, I think),
but rather it's a scoping issue.

class A
m = Module.new{define_method:)foo){"bar"}}
include m
end

I tried this third version :)

irb(main):004:0* $m = Module.new
=> #<Module:0x40233040>
irb(main):005:0> $m.module_eval do
irb(main):006:1* def self.a()""end
irb(main):007:1> def b()1;end
irb(main):008:1> end
=> nil
irb(main):009:0> $m.a
=> ""
irb(main):010:0> class A
irb(main):011:1> include $m
irb(main):012:1> end
=> A
irb(main):013:0> a = A.new
=> #<A:0x4020ec54>
irb(main):014:0> a.b
=> 1

it seems indeed that plain *m* is not seen
are constants handled special? (because M is seen)
and are globals seen anyway
or is this irb issue?

Thx, Daniel
 

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

Forum statistics

Threads
474,206
Messages
2,571,069
Members
47,678
Latest member
Aniruddha Das

Latest Threads

Top