J
Jim Weirich
In the Method Redefinition thread, this explanation of Duck Typing is
offered ...
This is slightly different than my understanding of Duck Typing. I
would phrase it more like this:
Duck typing is based mostly on realising what sort of operations
you want to do with the object and just doing them, rather than
worrying if the object inherits from the proper base class or
interface.
I've heard others also explain duck typing in terms of explicitly
testing for particular methods and I feel that leaves the wrong
impression. If we say Ruby supports duck typing, then newcomers are
left with the impression that you need to do a lot of testing for
particular methods (which you don't).
I would call this an example of Duck Typing ...
class Dog
def talk
puts "Woof"
end
end
class Duck
def talk
puts "Quack"
end
end
[Dog.new, Duck.new].each { |a| a.talk }
... even though there is no explicit method testing going on. After
all, if it walks and talks like a duck ...
So, am I off base?
offered ...
What Duck typing is based mostly on realising what sort of operations
you want to do with the object and testing for those operations,
rather than testing for the class. As Dave is fond of saying: type and
class aren't the same.
This is slightly different than my understanding of Duck Typing. I
would phrase it more like this:
Duck typing is based mostly on realising what sort of operations
you want to do with the object and just doing them, rather than
worrying if the object inherits from the proper base class or
interface.
I've heard others also explain duck typing in terms of explicitly
testing for particular methods and I feel that leaves the wrong
impression. If we say Ruby supports duck typing, then newcomers are
left with the impression that you need to do a lot of testing for
particular methods (which you don't).
I would call this an example of Duck Typing ...
class Dog
def talk
puts "Woof"
end
end
class Duck
def talk
puts "Quack"
end
end
[Dog.new, Duck.new].each { |a| a.talk }
... even though there is no explicit method testing going on. After
all, if it walks and talks like a duck ...
So, am I off base?