tags:

views:

31

answers:

1

This is strictly theoretical.

module BleeTest
  def meth
    puts 'foo'
  end
end

This code runs without error, but is it ever possible the invoke the method "meth"?

It seems to me that "meth" is an instance method of a module which cannot be instantiated. But then why is this construct allowed by the interpreter?

+6  A: 

Yes, of course. You can mix BleeTest into an object:

o = Object.new
o.extend BleeTest

o.meth
# foo

Or you can mix BleeTest into a class:

class C
  include BleeTest
end

o = C.new

o.meth
# foo

In fact, the first form can also be expressed in terms of the second form:

o = Object.new

class << o
  include BleeTest
end

o.meth
# foo

That is, after all, the whole point of modules in Ruby: to serve as mixins in order to compose objects and classes.

Jörg W Mittag
unfortunately you can only `bind` the method to an instance of a subclass of `BleeTest`. `m.bind(o).call #=> TypeError: bind argument must be an instance of BleeTest`. So doing this works fine: `o.extend(BleeTest); m.bind(o).call #=> foo`
banister
Thank you, that helps to clarify some gem source code I am reading through.
Jörg W Mittag