David and Sharon Phillips
7/8/2007 3:22:00 AM
On 08/07/2007, at 12:28 PM, Ari Brown wrote:
> Hey,
> Just a curious question.
>
> So does ruby have anything to accommodate for it? If not, what
> about a work around?
>
> Thanks,
> ~ Ari
> English is like a pseudo-random number generator - there are a
> bajillion rules to it, but nobody cares.
>
>
Do you mean something like this (example below)?
What you should be aware of is that Ruby doesn't require you to cast
objects to a particular type in order to call a method. You may have
a number of objects of completely different classes in your
collection, and as long as they all respond to the method you're
interested in then you can iterate through and call that method (duck
typing). This makes interfaces redundant and is a fantastically
useful feature.
Cheers,
Dave
class Animal
attr_reader :name
def initialize(name)
@name= name
end
def noise
"some strange grunty sound"
end
end
class Dog < Animal
def noise
"Woof!"
end
end
class Cat < Animal
def noise
"Meow"
end
end
animals= [Dog.new("Fido"), Cat.new("Socks"), Animal.new("Suzi")]
animals.each do |animal|
puts "#{animal.name} says #{animal.noise}"
end
>
Fido says Woof!
Socks says Meow
Suzi says some strange grunty sound