尝试实例化新类时,获取未初始化的常量错误

时间:2016-10-31 14:49:12

标签: ruby class inheritance subclass

我收到错误:

lynda.rb:206:in `<main>': uninitialized constant Pig (NameError)

当我尝试实例化猪类的新实例时。有谁知道为什么我收到这个错误?我在网上搜索过,我被告知这通常是因为不需要你的父班。但是我的父类在同一个文件中。

class Animal
  attr_accessor :name
  attr_writer :colour
  attr_reader :legs, :arms

 def initialize(noise,legs=4,arms=0)
    @noise = noise
    @legs = legs
    @arms = arms

    puts "A new animal has been instantiated"
 end

 def noise=(noise)
    @noise = noise
 end

 def noise
    @noise
 end



  class Pig < Animal
   def noise
      parent_method = super
      puts "Hello and #{parent_method}"
   end
 end

  class Cow < Animal
  end
end

piggy = Pig.new("oink")
p piggy.noise

1 个答案:

答案 0 :(得分:2)

您在Pig类中定义了Animal类。

尽管事实上,很可能不是你想要的那样,但是要解决你想要正确引用该类的问题:

piggy = Animal::Pig.new("oink")

定义Pig类之外的CowAnimal类,这意味着在打开Animal之前关闭Pig类。这样您就可以使用以下方法对其进行实例化:

 piggy = Pig.new("oink")