我有一个对象Animal,当我传入一个类型时,我选择其中一个子类并在那里实例化它。如下所示:
class Museum::Animal
def initialize type
case type
when "cat"
CatAnimal.new
when "dog"
DogAnimal.new
end
end
end
但是Rails给了我错误:预期..file路径../animal.rb来定义Animal
有问题的文件位于lib / museum / animal.rb
答案 0 :(得分:2)
module Barn
# parent class
class Animal
def say
'default'
end
end
# inheritance for cat
class Cat < Animal
def say
"meow"
end
end
#inheritance for dog
class Dog < Animal
end
# Factory to get by "type"
def self.get type
case type
when :dog
Dog.new
when :cat
Cat.new
end
end
end
并将其存储为lib / barn.rb。然后你可以这样做:
require 'barn'
c = Barn.get :cat
=> #<Barn::Cat:0x0000010719ffe8>
c.say
=> "meow"
d = Barn.get :dog
=> #<Barn::Dog:0x00000107190408>
d.say
=> "default"