Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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.

like image 438
Sanjay Salunkhe Avatar asked Mar 12 '26 01:03

Sanjay Salunkhe


1 Answers

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.

like image 175
Andrey Deineko Avatar answered Mar 14 '26 15:03

Andrey Deineko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!