From: Eric Mahurin Date: 2005-09-09T07:05:00+09:00 Subject: Re: Lexical Casts with Ruby --- Paul Brannan wrote: > On Fri, Sep 09, 2005 at 03:49:59AM +0900, Eric Mahurin wrote: > > class String > > def self.from(obj); obj.to_s; end > > def to(klass); klass.from_s(self); end > > end > > > > If you did this, then I guess you could consider this the > > overhead for each class that other classes want to convert > > to/from - String, Integer, Float, Array, etc. > > > > I would think this more straight-forward approach would be > more > > likely accepted. > > Would you be more amenable to a solution like: > > class Object > def to(type, *args, &block) > return send("to_#{type}", *args, &block) > end > > def to_String > return to_s > end > end > > class String > def to_Integer > return Integer(self) > end > > # etc. > end > > This eliminates the global constant by using double-dispatch, > plus > retains the ability to convert to a non-class type (e.g. > foo.to(Enumerable)). > > Paul Let's say you have some aribitrary class that you want to convert to/from a string. With the above, you'd put the to-string method in this class and the from-string method in String. I think better encapsulation would be to put both of these in this new aribitrary class. To do it this way and force the method names to have the class name in them, you'd do this: class Object def self.from(obj,*args,&block) send("from_#{self}".to_sym,obj,*args,&block) rescue obj.send("to_#{self}".to_sym,*args,&block) end def to(klass,*args,&block) send("to_#{klass}".to_sym,*args,&block) rescue klass.send("from_#{self.class}".to_sym,self,*args,&block) end def to_String to_s end def to_Integer to_i end end class Xyz def self.from_String(s,base=10) ... make a Xyz from s ... end def to_String(base=10) ... make a String from self ... end end Of course in the above, "klass" doesn't have to be a Class, but it does need to respond to the right from_* method. I'm not sure of the value of using from_String/to_String over from_s/to_s. I think you'll have just a few classes that you'll have many classes converting from/to them. You'll never be able to convert from one arbitrary class to another. Also, the above code is kind of ugly forming method names and trying two different methods (not very duck-type like) - but I could get over it. Would this work with the non-class types you are talking about? ______________________________________________________ Click here to donate to the Hurricane Katrina relief effort. http://store.yahoo.com/redcross-donate3/