On Wed, 16 May 2001, Hal E. Fulton wrote: > Hello all, > I was thinking about this today. I'd like to be able to define > some "ways of sorting" objects (i.e., by different fields) > and just plug them in. > Passing a block to "sort" is neat, but it's a little more > intrusive than I have in mind. > class Array > def sortBy(sym) > expr = sym.id2name + "(x,y)" > self.sort { |x,y| instance_eval(expr) } > end > end > def Str(x,y); x.str <=> y.str; end > def Int(x,y); x.int <=> y.int; end > def Chr(x,y); x.chr <=> y.chr; end > a = x.sortBy :Str > b = x.sortBy :Int > c = x.sortBy :Chr class Array def sort_by(sym) self.sort {|x,y| x.send(sym) <=> y.send(sym) } end end or: class Array def sort_by(sym) self.sort(&eval %{ proc {|x,y| x.#{sym} <=> y.#{sym} } }) end end The latter should be faster. warning: Haven't tried either. matju