[RUBY] 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)
6th class: Variables, 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
11th class: Class
Map method
Abstract method
initialize method
List method
puts method
Java method
save! method
getParameter method
[Java] method
ObjectMapper class
private method
rails method
ArrayList class
[Java] method
[Java] Instance method, instance field, class method, class field, constructor summary
Java class methods
Class and model
[Java] Class inheritance
9th class: assert_equal
Ruby to_s method
Binary search binary search method
Java HashMap class
Java method call from RPG (method call in own class)
10th class: Recursion
Method to search
Factory Method Pattern
About class inheritance.
java (abstract class)
Exception switching method
RxSwift method chain
Rails delegate method
Java8 method reference
Class in Ruby
[Ruby] slice method
[Ruby] end_with? method
[Ruby] Method memorandum
[Java SE 11 Silver] Arrays class method summary [Java beginner]
[HTTP method PATCH]
[Java] Nested class
About the method
Java anonymous class
[Practice] Map method
[Servlet] Basic method
variable and method
About Java class
Binary search method
Template Method pattern
0-filled (non-zero) method
8th class: rake
JavaSilver11 study method