A factory method in Ruby is a design pattern used to create objects. It provides a way to encapsulate the instantiation logic of objects, allowing for more flexible and maintainable code. The factory method can be defined in a class to create instances of that class or other classes.
Factory methods are often used in object-oriented programming to create objects without exposing the instantiation logic to the client code. This can help decouple the client code from the concrete classes being created, making it easier to change or extend the object creation process.
Here's an example of a factory method in Ruby:
class Animal
def self.create(type)
case type
when :dog
Dog.new
when :cat
Cat.new
else
raise "Unknown animal type: #{type}"
end
end
end
class Dog
def speak
"Woof!"
end
end
class Cat
def speak
"Meow!"
end
end
In this example, the Animal class has a factory method create that takes a type and returns an instance of the corresponding class (Dog or Cat). This approach centralizes the object creation logic and makes it easier to manage and extend.