我收到一个错误:
lynda.rb:206:in `<main>': uninitialized constant Pig (NameError)
当我尝试实例化Pig类的新实例时。有人知道为什么我会收到此错误吗?我已经在网上搜索过,并且被告知这通常是由于不正确地要求您的家长上课。但是,我的父类在同一个文件中。
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
您在Pig
类内部定义了Animal
类。
尽管有这样的事实,但很可能不是您想要的那样,而是要解决您要正确引用该类的问题:
piggy = Animal::Pig.new("oink")
在类之外定义Pig
和Cow
类Animal
,这意味着Animal
在打开之前关闭类Pig
。这样,您就可以使用以下方法实例化它:
piggy = Pig.new("oink")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句