From: "Florian Groß" Date: 2005-12-24T08:32:00+09:00 Subject: Re: How to sort this hash? x1 wrote: > Is it possible to sort the jobs hash below based on values such as > command, start_time and stop_time? > > Ideally, sort_by would be dynamically provided and I would output the > jobs entries based on the value defined for sort_by. > > sort_by = "start_time" #<---- I'd like to use something like this to > define which job is listed first > > jobs = { > "2231" => {"command" => "test_a.bash", > "start_time" => "20051211", > "stop_time" => "20051222"}, > "1131" => {"command" => "test_b.bash", > "start_time" => "20051011", > "stop_time" => "20051122"}, > "231" => {"command" => "test_c.bash", > "start_time" => "20051215", > "stop_time" => "20051227"} > } sort_keys = ["start_time", "stop_time"] jobs.sort_by do |job| sort_keys.map do |key| job[key] end end Note that this will only work as long as all sort_keys are present in every job. You might want to check the documentation for Enumerable#sort_by, but let me document the special thing in this case as well. sort_by's block can return multiple values as an Array. In that case it will first sort by the first value then by the second one and so on. This is used in the above sample where every job is sorted by the fields representing the sort_keys on that specific job. -- http://flgr.0x42.net/