Why can the instance method be called as a module method after inclusion?

The instance method defined in the module:

module A def foo; :bar end end 

It seems that it can be called as a modular method of this module when this module is enabled:

 include A A.foo # => :bar 

Why is this?

+4
source share
2 answers

You include A in Object.

 module A def self.included(base) puts base.inspect #Object end def foo :bar end end include A puts A.foo # :bar puts 2.foo # :bar #puts BasicObject.new.foo #this will fail 

Also note that the top-level object main is special; it is both an instance of an object and a kind of object divider.

See http://banisterfiend.wordpress.com/2010/11/23/what-is-the-ruby-top-level/

+7
source

Tried this in irb, he included it in Object . include A also returns Object

 irb > module A irb > def foo; :bar end irb > end => nil irb > Object.methods.include? :foo => false irb > include A => Object irb > Object.methods.include? :foo => true 
0
source

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


All Articles