[英]uninitialized constant Cat (NameError) during Ruby exercise
我是新来的,并且有关于类继承的问题。 我正在做一个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
您的Cat
和Dog
类在Pet
范围内声明,因此如果要创建Cat
对象,则必须编写
c = Pet::Cat.new("red", "Maine coon")
要以您的方式创建Cat
对象,您必须在Pet
类之外提取Cat
类。
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")
尝试Cat = Pet::Cat
您还可以创建一个module
并使用include
或只在内核范围内声明Cat类
或致电Pet :: Cat.new
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.