Paul Duca Paul Duca - 5 months ago 6
Ruby Question

Defined method comes up undefined?

I was trying to recreate an example from beginning ruby by Peter Cooper.

class Animal
attr_accessor :name

def initilize(name)
@name = name
end
end

class Cat < Animal
def talk
puts "Meow!"
end
end

class Dog < Animal
def talk
puts "Woof!"
end
end

class Cow < Animal
def talk
puts "Moo!"
end
end

class Sheep < Animal
def talk
puts "Bahhhh"
end
end

animals = [Cat.new.initilize("Tiger"), Dog.new.initilize("Ginger"), Cow.new.initilize("Gretta"), Sheep.new.initilize("Sally")]

animals.each do |x|
x.talk
end


Various attempts including calling the method separately do not seem to work. I'm not sure if the problem is with inheritance. Please help.

Answer

There are a few problems with your code:

  1. It's spelled initialize, not initilize. Methods with this name defined on classes are special because they return an instance of the class.

  2. When you do something like this: Cat.new.initilize("Tiger") that is incorrect. You will never manually call the initialize method. It automatically gets run when you call Cat.new("Tiger") and has the arguments passed to it.

Comments