From: Markus Date: 2004-10-13T01:05:13+09:00 Subject: Re: [Q] case based on object class Very interesting. This is a case where extending the base classes could certainly be justified; adding a "from_s" method that was the inverse of "to_s" would do the job nicely. It's tempting to use one of the other extant techniques, but none of them have the requisite generality, so we write: WARNING: CODE TYPED DIRECTLY INTO E-MAIL def Object.from_s(s); s; end def String.from_s(s); s.to_s; end def Fixnum.from_s(s); s.to_i; end def Float.from_s(s); s.to_f; end def Time.from_s(s); Time.parse(s.to_s()); end : and so forth. Then you can write something like "klass.from_s(val)" in your routine. The main reason for doing it this way is the extensions to the basic classes are of general utility; they are often called things like "parse," "from," or "called" (e.g. Integer.called("48")). A second reason for doing it this way is that it becomes easier to add additional classes to the system (e.g. SQL enumerations) "on the fly". -- Markus On Tue, 2004-10-12 at 01:09, George Moschovitis wrote: > > If the original poster is still reading, what is the real > > application? Is there some reason you need to know the class, or do you > > just need to assure that the class has some behaviour? > > here is a snippet from the real application (ndb). I want to make the > following code more elegant (I dont care for efficiency this code only > runs once :)) > > 102 s, klass = prop.symbol, prop.klass > 103 > 104 module_eval %{ > 105 def #{s} > 106 return @#{s} > 107 end > 108 > 109 def #{s}=(val) > 110 @#{s} = val > 111 end > 112 > 113 def __force_#{s}(val) > 114 @#{s} = } + case klass.name > 115 when Fixnum.name > 116 "val.to_i()" > 117 when String.name > 118 "val.to_s()" > 119 when Float.name > 120 "val.to_f()" > 121 when Time.name > 122 "Time.parse(val.to_s())" > 123 when TrueClass.name, FalseClass.name > 124 "val.to_i() > 0" > 125 else > 126 "val" > 127 end + %{ > 128 end > 129 } > 130 end > > > regards, > George Moschovitis