From: Erik Veenstra Date: 2007-02-15T22:35:46+09:00 Subject: Re: sorting an array of hash > mime_types.sort!{|mime_type1,mime_type2| > mime_type1['type'] <=> mime_type2['type'] > } > > it's working very well ;-) But it's inefficient... (See benchmark below.) You're doing a lookup in both hashes in order to compare the types. A more efficient technique is to cache theses types. Sort_by constructs a temporary array, where each element is an array containing the type along with the mime type. Sort_by than sorts this array, and extracts the mime type from the result. gegroet, Erik V. - http://www.erikveen.dds.nl/ ---------------------------------------------------------------- $ cat test.rb require "benchmark" array = (1..100_000).collect do {:thing => rand} end Benchmark.bmbm do |bm| bm.report("sort") do 10.times do array.sort do |h1, h2| h1[:thing] <=> h2[:thing] end end end bm.report("sort_by") do 10.times do array.sort_by do |h| h[:thing] end end end end ---------------------------------------------------------------- $ ruby test.rb Rehearsal ------------------------------------------- sort 76.360000 0.000000 76.360000 ( 76.510000) sort_by 7.391000 0.000000 7.391000 ( 7.391000) --------------------------------- total: 83.751000sec user system total real sort 46.967000 0.000000 46.967000 ( 47.047000) sort_by 7.191000 0.000000 7.191000 ( 7.190000) ----------------------------------------------------------------