Sorting an array of hash

i do have an array of hashes like that :

{type => aType, description => aDescription, extension => aExtension}

i’d like to sort this array by hash[‘type’], how to do that ?

this array represent the MIME Types.

On 15/02/07, Une Bévue [email protected] wrote:

Une Bévue

arrayOfHashes.sort_by{|hash| hash[‘type’]}

Farrel

Une Bévue [email protected] wrote:

i’d like to sort this array by hash[‘type’], how to do that ?

i did that that way :

mime_types.sort!{|mime_type1,mime_type2|
mime_type1[‘type’] <=> mime_type2[‘type’]
}

it’s working very well :wink:

is arrayOfHashes a special object in ruby ???

arrayOfHashes is your array of hashes. You’re calling it arr
and mime_types; he’s calling it arrayOfHashes.

i didn’t found #sort_by in the pikaxe pages for Array.

sort_by is defined in the module Enumerable. This module is
included (mixed-in?..) in Array.

gegroet,
Erik V. - http://www.erikveen.dds.nl/

Farrel L. [email protected] wrote:

arrayOfHashes.sort_by{|hash| hash[‘type’]}

fine thanks i did it that way :

arr.sort!{|a1,a2| a1[‘type’] <=> a2[‘type’]}

is arrayOfHashes a special object in ruby ???

i didn’t found #sort_by in the pikaxe pages for Array.

mime_types.sort!{|mime_type1,mime_type2|
mime_type1[‘type’] <=> mime_type2[‘type’]
}

it’s working very well :wink:

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)

Erik V. [email protected] wrote:

But it’s inefficient… (See benchmark below.)

it was a “one time running” script then…

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.

Ok i see.

gegroet,
Erik V. - http://www.erikveen.dds.nl/

Anyway, thanks a lot i’ve learned something today )))