One of the items I stumbled upon in Ruby, the class method. I will write what I did not understand.
Click here for classes and instances [link-1]. [link-1]:https://qiita.com/fishmans0120/items/569cd9ab37b89c0c1726
As a prerequisite, what is a method? A method is the "behavior" of the data.
If you think about it by applying it to a car, The actions that the data of a car has are "run, stop, turn signal" and so on.
A method that can be used by the class itself that defines the class method. It can be used for processing that has common information in the class. The definition method is the same as other methods, but prefix the method name with .self.
class Car def self.run #Define a class method by prefixing the method name with self puts "run" end end Car.run #name of the class.You can execute the defined class method by the method name
(Added on June 29, 2020. Thank you for pointing out: bow_tone1:) Alternatively, you can write a method between class << self and end. Nesting is one step deeper, but if you want to define a lot of class methods, you don't have to prefix the method name with .self every time.
class Car class << self def run puts "run" end end end
The notes of the class method are as follows.
-When defining, add .self before the method name. -Alternatively, there is a notation to write a method between class << self and end. -This method can be used only for classes.
Thank you for reading to the end.