From: Eric Mahurin Date: 2005-08-26T01:57:00+09:00 Subject: Re: idea: klass.from_s(str) --- Eric Mahurin wrote: > --- "Kroeger Simon (ext)" > wrote: > > > > > > [...] > > > If you have a klass#to_* method, you should have a > > > corresponding klass.from_* method if appropriate. This > > would > > > make your class more encapsulated, instead of having some > > of it > > > in String (or whatever class you are converting from). > > > > Perhaps implement a method_missing in String such as > s.to_xxx > > > > will call xxx.from_s ? > > > > cheers > > > > Simon > > > That sounds like a good idea to add a little convienence. > That > shows the power of starting with the xxx.from_s(str) method > instead of String#to_xxx where the class is > embedded/abbreviated in the method name. > > Here's a demo: > > class String > def method_missing(meth) > if m = /^to_(.*)$/.match(meth.to_s) > Class.const_get(m[1].capitalize.to_sym).from_s(self) > else > super > end > end > end > > class Abc > def self.from_s(s) > self.new(s) > end > def initialize(s) > @abc = s > end > def to_s > @abc.to_s > end > end > > Abc.from_s("hello") # => # > "hello".to_abc # => # Maybe this would be better - making the class an argument rather than embedding it in the method name: class String def to(klass) klass.from_s(self) end end Abc.from_s("hello") # => # "hello".to(Abc) # => # __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com