Class method

What is a class method?

Methods that are closely related to the class but do not use the data contained in each instance

How to define a class method 1

python


class class name
  def self.Class method
  #Processing class methods
 end
end
How to define a class method 2

python



class class name
  class << self
def class method
      #Processing class methods
    end
  end
end

When calling a class method, do as follows

python


name of the class.Method name

python


class Food
  def initialize(name)
    @name = name
  end

  #self.If you add, it becomes a class method
  def self.create_foods(names)
    names.map do |name|
      Food.new(name)
    end
  end

  #Instance method
 def eat
    "I will eat an #{@name}."
  end
end

names = ['apple', 'octopus']
#Calling a class method
foods = Food.create_foods(names)
foods.each do |food|
  puts food.eat
end

#=> I will eat an apple.
#   I will eat an octopus.

reference

An introduction to Ruby to become a professional

Recommended Posts

Class method
Java programming (class method)
Difference between instance method and class method
Java method
to_i method
java (method)
[Java] Object-oriented syntax --class method / argument
getRequestDispatcher () method
merge method
Map method
include method
Abstract method
Anonymous class (anonymous class)
initialize method
List method
puts method
Java method
save! method
getParameter method
[Java] method
ObjectMapper class
private method
rails method
ArrayList class
[Java] method
[Beginner] Java method / class / external library [Note 23]
[Java] Instance method, instance field, class method, class field, constructor summary
JDBC class load
Class and model
[Java] Class inheritance
Screen transition method
java Scanner class
Binary search binary search method
Decompile class files
Java method call from RPG (method call in own class)
Factory Method Pattern
java (abstract class)
Exception switching method
Rails delegate method
scan method problem
Java8 method reference
[Java SE 11 Silver] Arrays class method summary [Java beginner]
[HTTP method PATCH]
[Java] Nested class
About the method
Java anonymous class
[Java] forEach method
[Servlet] Basic method
About Java class
Binary search method
Template Method pattern
Template Method Pattern
0-filled (non-zero) method
JavaSilver11 study method
String class methods
keycloak test-skip method
Factory Method pattern
[Ruby] initialize method
java.lang.IncompatibleClassChangeError: Implementing class
Ruby build method
undefined method `** _ path'error