How can I access the class method and instance method in ruby?

Looking through some blogs and articles, I found that each class in Ruby is itself an instance of Class . What is the difference between class methods and instance methods and does ruby ​​allow an object to be created?

I'm trying to do something like this, but still can't understand

 str = Class.new(String) => #<Class:0xb5be1418> my_str = str.new() => "" my_str = str.new("hello") => "hello" my_str.class => #<Class:0xb5be1418> str.class => Class 

NOW FULLY SLOW

+6
source share
2 answers
 class Dog # Returns the number of dog objects created using this class def self.count end # Returns name of the dog object def name end end 

In the above example, the general method (which is associated with all objects of the dog) is called the class method .

The method associated with a particular dog (dog object) is called the instance method .

According to object models, ruby ​​Dog is constant , which points to an instance of the Class class. Whenever a class method is added to Dog, a new class called Metaclass will be added to the class Metaclass to save the class methods.

0
source

In the first sentence, you create an anonymous class with the superclass String :

 my_str.class.superclass # => String 

But this is not the essence of your current question :)

An instance is an object of a certain class: String.new() # creates instance of class String . Instances have classes (String.new()).class #=> String . All classes are instances of the class Class : String.class # => Class . Class instances also have the superclass class - which they inherit.

An instance method is a method that you can call on an instance of an object.

 "st ri ng".split # split is an instance method of String class 

A class method in Ruby is a general term, for example, for methods of the Class class (any class).

 String.try_convert("abc") # try_convert is a class method of String class. 

Read more about instance and class methods in this article .

+4
source

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


All Articles