3

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.

1

1 Answer 1

3

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.

9
  • Due to this behaviour you could call show on anything, even a number 5.show
    – sokkyoku
    Commented Sep 8, 2016 at 13:38
  • but i have not included module "A" inside "Object" class ?? Commented Sep 8, 2016 at 13:47
  • @sanjay including in the outermost scope means include'ing into Object :) Commented Sep 8, 2016 at 13:47
  • 1
    @sanjay absolutely Commented Sep 8, 2016 at 13:51
  • 1
    No, methods defined at the top-level are private in Ruby. They are, however, public in IRb. This is one of the ways in which IRb differs from Ruby. Some other differences are corner cases in local variable handling, and some syntax that is legal in Ruby but rejected by IRb. Moral of the story: don't use IRb to verify Ruby behavior. Commented Sep 8, 2016 at 21:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.