From: dblack@... Date: 2006-03-16T22:02:45+09:00 Subject: Re: Variant types Hi -- On Thu, 16 Mar 2006, Stefan Haflidason wrote: > My languages lecturer is a fan of a feature called 'variant' in a model > language he defined. The variant declaration is used to specify that a > variable may be of one or another type. > > When he stated that no languages we are taught have this functionality, > I asked him whether using an abstract class which is subclassed for > each variant type would be enough. He said that this would work, but is > a form of encoding the declaration and as such is not as good as such a > declaration provided as part of the language. > > I had a go at implementing 'variant' in Ruby. I'm going to show it to > him tomorrow and see what he thinks. Comments welcome. > > Variant takes the name of the property, and one or more types. I > haven't seen him use this for more than two types however. > > Can anyone see a way to do away with the instance variables? I could > have made them methods, but this does not seem to offer additional > encapsulation. > > Code: > > class Class > > def variant(name, *classes) You're right to call your variable classes, rather than types. In Ruby, an object's type is not the same as its class. The type of an object is basically the sum of its various capabilities at a given moment in runtime. Some of those capabilities come from the object's class, but not necessarily all; and the object's type can change. There are already some packages out there that do class/ancestry checking (and sometimes refer to it as "type" checking). Actual type-checking is much harder in Ruby, perhaps even impossible, though there have also been some interesting experiments along those lines. It's an interesting exercise to do class-checking, but keep in mind that it doesn't really address object type, and also that you're unlikely to need it beyond the exercise stage :-) David -- David A. Black (dblack@wobblini.net) Ruby Power and Light, LLC (http://www.rubypowerandlight.com) "Ruby for Rails" chapters now available from Manning Early Access Program! http://www.manning.com/books/black