简体   繁体   中英

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:

uninitialized constant Cat (NameError)

Also, I get it when I take out the Cat information, and Dog is not initialized.

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.

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

c = Pet::Cat.new("red", "Maine coon")

To create Cat object the way you do you have to extract Cat class outside Pet class.

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

You could also create a module and use include

or just declare the Cat class in the Kernel scope

or just call Pet::Cat.new

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM