Find out about class methods

Yesterday I looked up instance methods This time we will look at class methods

Define a class method

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

Actually move

app/models/calculation.rb


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~

Then, NoMethodError occurs

app/models/calculation.rb


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

Summary

-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 "

Reference article

Cherry book https://qiita.com/right1121/items/c74d350bab32113d4f3d https://qiita.com/right1121/items/c3997653a621c74fb97d

Recommended Posts

Find out about class methods
Find out about Docker
Find out about instance methods and self
About Java class variables class methods
Find out about annotationProcessor for Gradle 5.0
Find out about environment variables (memo)
Java class methods
About class inheritance.
About singular methods
About HttpServlet () methods
About Java class
String class methods
About Ruby methods
About the StringBuilder class
About class division (Java)
About Java StringBuilder class
[Java] About Singleton Class
About Ruby instance methods
About calling instance methods
[Swing] About JFrame class
About Java String class
About sorting java.util.Arrays class
About java abstract class
About validation methods in JUnit
About the File :: Stat class
About Java class loader types
Find out all timezone IDs supported by the Java TimeZone class
About naming Rails model methods
About pluck and ids methods
What are Ruby class methods?
[Ruby] Class methods, instance methods, etc.
About methods often used in devise
About Java static and non-static methods
Various methods of Java String class
About the equals () and hashcode () methods
Various methods of the String class
A murmur about the utility class
[For our newcomers] About isXXX methods
How to use class methods [Java]
Differences between find, find_by, find_by_sql methods
How to find out the Java version of a compiled class file
Where can I find out about Java releases after February 2019? About the problem