Methods that are closely related to the class but do not use the data contained in each instance
python
class class name
def self.Class method
#Processing class methods
end
end
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.
An introduction to Ruby to become a professional
Recommended Posts