Can I call the module instance_modod method?

This is strictly theoretical.

module BleeTest
  def meth
    puts 'foo'
  end
end

This code works without errors, but is it possible to ever call the meth method?

It seems to me that "meth" is a module instance method that cannot be created. But then why is this construction allowed by the interpreter?

+3
source share
1 answer

Yes of course. You can mix BleeTestinto an object:

o = Object.new
o.extend BleeTest

o.meth
# foo

Or you can mix BleeTestinto a class:

class C
  include BleeTest
end

o = C.new

o.meth
# foo

Indeed, the first form can also be expressed through the second form:

o = Object.new

class << o
  include BleeTest
end

o.meth
# foo

That is, in the end, the whole point of modules in Ruby: serves as mixins for linking objects and classes.

+8
source

Source: https://habr.com/ru/post/1759015/


All Articles