我是新来的,并且有关于类继承的问题。我正在做一个CareerFoundry项目,我似乎无法找到为什么我一直收到错误:
未初始化的常量Cat(NameError)
另外,当我取出Cat信息时,我得到它,并且Dog未初始化。
我认为这意味着我没有正确地写出Cat是Pet课程的一部分,但我想我会把这个问题扔给社区,希望有答案。
class Pet
attr_reader :color, :breed
attr_accessor :name
def initialize(color, breed)
@color = color
@breed = breed
@hungry = true
end
def feed(food)
puts "Mmmm, " + food + "!"
@hungry = false
end
def hungry?
if @hungry
puts "I\'m hungry!"
else
puts "I\'m full!"
end
@hungry
end
class Cat < Pet
def speak
puts "Meow!"
end
end
class Dog < Pet
def speak
puts "Woof!"
end
end
end
kitty = Cat.new("grey", "Persian")
"Lets inspect our new cat:"
puts kitty.inspect
"What class is this new cat"
puts kitty.class
puppy = Dog.new("Black", "Beagle")
puppy.speak
puts puppy.breed
答案 0 :(得分:3)
您的Cat
和Dog
类在Pet
范围内声明,因此如果您想创建Cat
对象,则必须编写
c = Pet::Cat.new("red", "Maine coon")
要按照您的方式创建Cat
对象,您必须在Cat
课程之外提取Pet
课程。
class Pet
attr_reader :color, :breed
attr_accessor :name
def initialize(color, breed)
@color = color
@breed = breed
@hungry = true
end
def feed(food)
puts "Mmmm, " + food + "!"
@hungry = false
end
def hungry?
if @hungry
puts "I\'m hungry!"
else
puts "I\'m full!"
end
@hungry
end
end
class Cat < Pet
def speak
puts "Meow!"
end
end
class Dog < Pet
def speak
puts "Woof!"
end
end
现在你可以简单地写
c = Cat.new("red", "Maine coon")
答案 1 :(得分:0)
尝试Cat = Pet::Cat
您还可以创建module
并使用include
或者只是在内核范围中声明Cat类
或只是致电Pet :: Cat.new