[Ruby] Class method

less than 1 minute read

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

Tags:

Updated: