尝试实例化新 class 时出现未初始化常量错误
Getting uninitialized constant error when trying to instantiate a new class
我收到一个错误:
lynda.rb:206:in `<main>': uninitialized constant Pig (NameError)
当我尝试实例化猪的新实例时 class。有谁知道我为什么会收到此错误?我在网上搜索过,有人告诉我这通常是因为没有正确要求您的 parent class。但是我的 parent class 在同一个文件中。
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
您在 Animal
class.
中定义了 Pig
class
尽管事实很可能不是您想要的,但要解决您希望正确引用 class 的问题:
piggy = Animal::Pig.new("oink")
在Animal
class之外定义Pig
和Cow
class,意思是关闭Animal
class 在打开 Pig
之前。这样你就可以实例化它:
piggy = Pig.new("oink")
我收到一个错误:
lynda.rb:206:in `<main>': uninitialized constant Pig (NameError)
当我尝试实例化猪的新实例时 class。有谁知道我为什么会收到此错误?我在网上搜索过,有人告诉我这通常是因为没有正确要求您的 parent class。但是我的 parent class 在同一个文件中。
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
您在 Animal
class.
Pig
class
尽管事实很可能不是您想要的,但要解决您希望正确引用 class 的问题:
piggy = Animal::Pig.new("oink")
在Animal
class之外定义Pig
和Cow
class,意思是关闭Animal
class 在打开 Pig
之前。这样你就可以实例化它:
piggy = Pig.new("oink")