Finding a method for singleton methods in a class in Ruby

I got the impression that obj.methodmade the ruby ​​look methodlike this:

  • Check out objthe singleton class.
  • Check out the modules included in the objsingleton class .
  • Look in the classroom obj.
  • See modules included by objclass
  • repeat steps 3 and 4 above the class superclass until you find
  • If this is not found, call method_missingon the source object obj.

In this model, a single syntax class only that searches method is a singleton source receiver class obj. However, this model cannot explain the fact that a subclass can access its single-user superclass methods. for instance

class Foo
  def self.foo
    "foo"
  end
end

class Bar < Foo
end

Bar.foo  #=> "foo"

I am confused because I believe that this means that the Foosingleton class is at some point looking for a method Foo. However, according to the model above, I would expect only a Barsingleton class to search Foo. Otherwise, I would expect ruby ​​to look into the class Bar, Classand then continue scanning along the superclass chain (skipping Fooits singleton class as well).

, : Ruby, , Singleton ?

+3
2

Bar.superclass Foo, :

Bar.singleton_class.superclass == Foo.singleton_class  # => true

, . :

  • obj singleton.
  • :
    • (Ruby 2.0)
  • # 2 .
  • # 1, method_missing
+8

. , :

The metaclass of the superclass is the superclass of the metaclass.

"metaclass" "singleton class". , , Bar.superclass Foo.superclass. :)

+3

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


All Articles