Jack Kelly Jack Kelly - 1 month ago 13
Ruby Question

Getting uninitialized constant error when trying to instantiate a new class

I'm receiving an error:

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


when I try to instantiate a new instance of the pig class. Does anyone know why I'm getting this error? I have searched online and I've been told it is commonly due to not requiring your parent class properly. However my parent class is within the same file.

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

Answer

You defined Pig class inside Animal class.

In spite of the fact, that it is most likely not what you intended it to be, to solve the problem you'd want to reference the class correctly:

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

Define the Pig and Cow classes outside of Animal class, meaning, close the Animal class before opening the Pig. This way you'll be able to instantiate it with:

 piggy = Pig.new("oink")