[英]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.