From: Chris Pine Date: 2003-03-24T13:13:31+09:00 Subject: Re: Ruby lecture slides (was Strong advantages over Python) ----- Original Message ----- From: "Greg McIntyre" > So I have implicity "defined" a duck type without ever making a Duck > class. In Java I would need a class or an interface or something, but > in Ruby that's all behond the scenes. Er... in this example you have an object of class String with an extra method. IMO, this is still of class String. ---------------------------- Yes, its *class* is still String. I was talking about its *type* (or its many types). Consider the following C++ code: class Point { int x; int y; } int getXfromPoint (Point p) { return p.x; } (Bare with me; my C++ is rusty!) The function getXfromPoint accepts as its argument the type Point, which is exactly those objects of class Point. Now consider the Ruby version: class Point attr_accessor :x, :y end def getXfromPoint (p) p.x end What is the type accepted by getXfromPoint this time? It is incorrect to say that it would accept anything. It accepts any object which responds to the `x' method. It accepts any object it can! So in Ruby, Point is a type (I guess), but so is objects-which-respond-to-`x', which has no associated class. Going back to the original example, of course it was still a string, but after `quack' was defined, it was also a duck. Moreover, I could create a string type (i.e. an object which responds to every method a string does) which is not an instance of the String class: myString = Object.new class << myString def reverse ... end def downcase ... end ... end Of course, if you want to avoid singletons, I could have done the same in a normal class: class MyString def reverse ... end ... end That, as I understand it, is "duck typing", and why we say that types and classes are two different things in Ruby. Chris