From: ahoward@... (ara howard) Date: 2002-09-20T02:01:00+09:00 Subject: alias/method redfinition it seems alias/method redefing can be a slipery slope. i wanted to make the Array class indexable by field name for some postgres work i was doing. i use the following method of redefining the [] and []= methods of the Array class, can any one comment on the effectiveness of this technique? USAGE : tuple = [0,1,2] tuple.fields = ['zero','one','two] puts tuple['zero'] -> 0 puts tuple['one'] -> 1 puts tuple['two'] -> 2 IMPLEMENTATION : class Array def fields=(*fields) @fields = fields.flatten @fieldpos = Hash.new @fields.each_with_index {|f,i| @fieldpos[f] = i} # redef only once! if not @oldcalls @oldcalls = { '[]' => method('[]'), '[]=' => method('[]='), }; m = Module.new m.module_eval %q{ def [] idx if @fields and idx.type == String pos = @fieldpos[idx] return nil unless pos self[pos] else @oldcalls['[]'].call idx end end def []= idx, value if @fields and idx.type == String pos = @fieldpos[idx] if not pos pos = size @fieldpos[idx] = pos end self[pos] = value else @oldcalls['[]='].call idx, value end end } self.extend m end end attr :fields attr :fieldpos end implementation :