From: "Wesley J. Landaker" Date: 2003-08-28T05:48:59+09:00 Subject: Re: sorting on hash contents Apparently, Mark Probert recently wrote: > > Hi, all. > > Say I have a hash of 4 elements, val[1..3] and name > > h["a"] = "1,2,3,fred" > h["b"] = "4,1,2,jack" > h["c"] = "3,3,4,jill" > > How do I define: > > def sort_hash(field="val1") > h.each { |key, data| > (val1, val2, val3, name) = data.split(/,/) > # etc.. > end > > elegantly? > > One possibility is to write it out to a tempfile and use > the external `sort` command. Is there an easy pure-ruby > solution? Not a full answer (no time right now), but run this in irb and it should should give you some ideas: h = {} h["a"] = "1,2,3,fred" h["b"] = "4,1,2,jack" h["c"] = "3,3,4,jill" h.to_a h.to_a.sort_by { |el| el[1].split(/,/)[0] } h.to_a.sort_by { |el| el[1].split(/,/)[1] } h.to_a.sort_by { |el| el[1].split(/,/)[2] } h.to_a.sort_by { |el| el[1].split(/,/)[3] } Wes