You can clean things up a bit by changing Vehicle#new to:
class Vehicle
def self.new(model_name = nil)
klass = case model_name
when 'mountain bike' then Bike
# and so on
else Car
end
klass == self ? super() : klass.new(model_name)
end
end
class Bike < Vehicle
def self.new(model_name)
puts "New Bike: #{model_name}"
super
end
end
class Car < Vehicle
def self.new(model_name)
puts "New Car: #{model_name || 'unknown'}"
super
end
end
The last line of Vehicle.new with the ternary statement is important. Without the check for klass == self we get stuck in an infinite loop and generate the StackError that others were pointing out earlier. Note that we have to call super with parentheses. Otherwise we'd end up calling it with arguments which super doesn't expect.
And here are the results:
> Vehicle.new
New Car: unknown # from puts
# => #<Car:0x0000010106a480>
> Vehicle.new('mountain bike')
New Bike: mountain bike # from puts
# => #<Bike:0x00000101064300>
> Vehicle.new('ferrari')
New Car: ferrari # from puts
# => #<Car:0x00000101060688>