What is the slickest, most Ruby-like way to have a single constructor return an object of the appropriate type?
To be more specific, here's a dummy example: say I have two classes Bike
and Car
which subclass Vehicle
. I want this:
Vehicle.new('mountain bike') # returns Bike.new('mountain bike')
Vehicle.new('ferrari') # returns Car.new('ferrari')
I've proposed a solution below, but it uses allocate
which seems way too implementation-heavy. What are some other approaches, or is mine actually ok?
If I make a factory method that is not called1 new
or initialize
, I guess that doesn't really answer the question "how do I make a ... constructor ...", but I think that's how I would do it...
class Vehicle
def Vehicle.factory vt
{ :Bike => Bike, :Car => Car }[vt].new
end
end
class Bike < Vehicle
end
class Car < Vehicle
end
c = Vehicle.factory :Car
c.class.factory :Bike
1. Calling the method factory works really well in this instructional example but IRL you may want to consider @AlexChaffee's advice in the comments.