Ruby Object # define_method vs Module # define_method

Can someone clarify the differences between ruby ​​Object Object#define_method and Module#define_method and where are they commonly used?

+6
source share
2 answers

Object#define_method does not exist:

 o = Object.new o.define_method #NoMethodError: undefined method `define_method' for #<Object:0x1448a80> 

However, Object.define_method exists:

 Object.define_method #NoMethodError: private method `define_method' called for Object:Class 

This is because Object is an object of class Class , and Class is a subclass of Module :

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

Therefore, when you call Object.define_method , you call Module#define_method .

Just remember that classes are objects of class Class , and it will be as clear as mud!

+5
source

Object#define_method is actually Module#define_method .

 pry(main)> Object.method(:define_method).owner => Module pry(main)> Module.method(:define_method).owner => Module 
+5
source

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


All Articles