2015-04-04 105 views
0

我是新來的,並且有關於類繼承的問題。我做了CareerFoundry項目,我似乎無法找出爲什麼我不斷收到錯誤:在Ruby練習期間未初始化的常量貓(NameError)

uninitialized constant Cat (NameError)

而且,我得到它,當我拿出貓的信息,狗未初始化。

我想這意味着我不能正確編寫貓是寵物類的一部分,但我想我會這個問題拋出到社區,並希望有一個答案。

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 

回答

2

CatDog類在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") 
+0

非常感謝,它效果很好。這個練習並沒有把這個概括爲一個潛在的答案,所以謝謝你的幫助。 – DevShark 2015-04-06 08:40:24

0

嘗試Cat = Pet::Cat

您還可以創建一個module和使用include

或只是宣佈在內核範圍Cat類

或者理由t打電話給寵物:: Cat.new

相關問題