Yesterday I looked up instance methods This time we will look at class methods
There are two ways to define
class class name def self.Class method name #processing end end
If you have a lot of class methods you want to define You don't have to add self every time, so it's convenient because the amount of code to write is reduced!
class class name class << self def class method name #processing end end end
class Calculation def addition(a, b, c, d, e) puts a + b + c + d + e end end addition(1,2,3,4,5) #=> undefined method~
class Calculation def self.addition(a, b, c, d, e) puts a + b + c + d + e end end Calculation.addition(1,2,3,4,5) #=> 15
-What is a class method? The receiver is a class name and the method for that class name
-Useful when creating methods to change or refer to information related to the entire class
-When defining, "
def self. Class method name "
Cherry book https://qiita.com/right1121/items/c74d350bab32113d4f3d https://qiita.com/right1121/items/c3997653a621c74fb97d