Reputation: 31
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.
Upvotes: 0
Views: 84
Reputation: 26788
There are a few problems with your code:
It's spelled initialize
, not initilize
. Methods with this name defined on classes are special because they return an instance of the class.
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.
Upvotes: 3
Reputation: 1416
Your code is wrong at couple of places.
initilize
to initialize
.Cat.new.initilize("Tiger")
, you should do Cat.new("Tiger")
to create the object.After the code changes, you will get the desired results.
animals = [Cat.new("Tiger"), Dog.new("Ginger"), Cow.new("Gretta"), Sheep.new("Sally")]
animals.each {|x| puts x.talk}
will give
Meow!
Woof!
Moo!
Bahhhh
Upvotes: 2