How does Object know about the const_get method?

I read another question with an answer that mentions using the instance method Module#const_getto search for a class in a module. For instance:

module M
  class C
  end
end

p M.const_get 'C'
#=> M::C

I was interested in the method const_get, so I used riand found:

ri Module#const_get
...
This method will recursively look up constant names if a namespaced
class name is provided.  For example:

  module Foo; class Bar; end end
  Object.const_get 'Foo::Bar'
...

It appears to be Object::const_geta single point method. Using this in our context works:

module M
  class C
  end
end

p Object.const_get 'M::C'
#=> M::C

But nothing is described about this singleton method:

ri Object::const_get
Nothing known about Object::const_get
ri Object.const_get
Nothing known about Object.const_get

This confused me because I know what Moduleis Object, but is Objectnot Module:

Module.ancestors
#=> [Module, Object, Kernel, BasicObject]
Object.ancestors
#=> [Object, Kernel, BasicObject]

Also, I used the instance method Object#is_a?for validation and saw that I was wrong about this:

Module.is_a? Object
#=> true
Object.is_a? Module
#=> true

What started as an innocent request riled me to confusion throughout the entire Ruby object model.

  • Object.is_a? Module #=> true, Module Object?
  • Object const_get?
+4
3

singleton , , .

Ruby 2.5+ singleton_class:

Object.singleton_class.ancestors
# => [#<Class:Object>, #<Class:BasicObject>, Class, Module, Object, Kernel, BasicObject]

Module , , Object.

:

Object.ancestors
#=> [Object, Kernel, BasicObject]

Ruby , Class Object, Class.

+5

, Object :

  • Object - , Object.ancestors . , Object < Kernel , Object < Module - false.
  • Ruby , Class. , Object.is_a? Class Object.is_a? Module , 'pancakes'.is_a? String. Object.const_get - , 'pancakes'.upcase .

some_obj.is_a? SomeClass some_obj.class.ancestors.include? SomeClass.

:

  • Object.is_a? Module #=> true, Module Object?

    is_a? ancestors .

  • Object const_get?

    Object Class Class Module . , 'pancakes' String, Kernel , 'pancakes' object_id.

+1

Object.is_a? Module #=> true

is_a? , Object ( ) Module. Class Module, Class Module. Object Class, Object Module.

Module#const_get

const_get - , Module. Object Module ( , ), Module#const_get.

0

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


All Articles