From: Nat Pryce Date: 2001-08-30T19:36:52+09:00 Subject: [ruby-talk:20573] Re: To those who want abstract classes in Ruby There is very little need for this in Ruby, and it can be a drawback. There is little need for this, by default, throws an exception when an object is sent a message it does not understand. It is a drawback because you now cannot instantiate an abstract class and define per-instance methods. E.g. code like this is very useful: a = Abstract.new def a.method_a( n ) ... end def a.method_b( n ) ... end ----- Original Message ----- From: "Matthias Lampert" To: "ruby-talk ML" Sent: Thursday, August 30, 2001 9:55 AM Subject: [ruby-talk:20571] To those who want abstract classes in Ruby > > Hi, folks! > > There are people who miss a feature like abstract/virtual > classes in Ruby. I was one of them, I admit. > > By the time I learned, though, that I could implement this > feature myself. Just like here. > > > ######################################################################### > class Abstract > attr :attrib > > def initialize( i_attrib ) > @attrib = i_attrib > check4ForbiddenInstantiating > end > > > def method_a > crash4ViolationOfAbstractness("method_a") > end > > def method_b > crash4ViolationOfAbstractness("method_b") > end > > > def crash4ViolationOfAbstractness( sMethodName ) > raise "Ahem... You need to implement " + > "#{self.type.to_s}##{sMethodName} to use it!" > end > > def check4ForbiddenInstantiating > if self.type.to_s == "Abstract" > raise "Sorry, lad! I'm abstract!" > end > end > > end > > > class Concrete < Abstract > def initialize( i_attrib ) > super(i_attrib) > end > > def method_a > puts "This instantiation is " + attrib.to_s > puts "Implemented Abstract#method_a" > end > end > > > # Abstract.new( "forbidden!") # ==> ERROR! > obj = Concrete.new("allowed!") > obj.method_a > # obj.method_b # ==> ERROR! > > ######################################################################### > > > It's primitive, I know that, but it's a place to get started, and it did > a great job for me so far. Maybe one of the gurus can make a module of it; > would be great to create an abstract class semi-automatically. Perhaps I > can do it myself, but I need to be a guru first! > > > CU, > > -- > > Matthias Lampert, Hamburg > Just another XP and Ruby fan >