sanjay sanjay - 1 year ago 42
Ruby Question

Why module included outside the class adds instance methods to class's objects

I am experimenting with the Ruby

include
keyword as shown below:

module A
def show
puts "working"
end
end

include A

class E
end

class D
end

e = E.new
d = D.new
e.show
d.show

o = Object.new
puts o.respond_to?("show")

******************************output****************

working
working
true


I was expecting output to be
undefined method
but it's giving me the proper output. I have also observed that the
show
method defined in
module A
is becoming an instance method of
Object
.

Why are these methods becoming instance methods of the class
Object
?
Please help in understanding this concept.

Answer Source

Because instances of class Class inherit from Object.

Thus, modules, included into Object are available to instances of Class's instances (instances of your E and D classes).

class A
end

module B
  def test; :hi end
end
#=> test

include B
#=> Object

A.new.test
#=> :hi

Object.new.test
#=> :hi

Having include B written in the top-level means include'ing B into Object.

include B is the outermost context is equivalent to:

class Object
  include B
end

The only class, whose instances do not share module B's methods is BasicObject.