[英]uninitialized constant Cat (NameError) during Ruby exercise
I am new here and having a question about Class inheritance. 我是新来的,并且有关于类继承的问题。 I am doing a CareerFoundry project, and I can not seem to find why I keep getting the error: 我正在做一个CareerFoundry项目,我似乎找不到我为什么不断收到错误的原因:
uninitialized constant Cat (NameError) 未初始化的常量Cat(NameError)
Also, I get it when I take out the Cat information, and Dog is not initialized. 另外,当我取出Cat信息并且不初始化Dog时,也会得到它。
I assume it means that I am not writing correctly that Cat is a part of the Pet class, but I thought I would throw out this question to the community and it hopefully has an answer. 我认为这意味着我没有正确地写出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
Your Cat
and Dog
classes are declared in Pet
scope so if you want to create Cat
object you have to write 您的Cat
和Dog
类在Pet
范围内声明,因此如果要创建Cat
对象,则必须编写
c = Pet::Cat.new("red", "Maine coon")
To create Cat
object the way you do you have to extract Cat
class outside Pet
class. 要以您的方式创建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
Now you can simply write 现在您可以简单地写
c = Cat.new("red", "Maine coon")
Try Cat = Pet::Cat
尝试Cat = Pet::Cat
You could also create a module
and use include
您还可以创建一个module
并使用include
or just declare the Cat class in the Kernel scope 或只在内核范围内声明Cat类
or just call Pet::Cat.new 或致电Pet :: Cat.new
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.