On Mar 13, 2007, at 5:45 AM, senthil wrote:

> HI all,
>      I want to sort a hash based on a attribute of the objects  
> which it
> is storing.For example i am having a bean diagnosis with weightage  
> as a
> attribute.i want to sort the hash of diagnosis based on the
> weightage.how to do this .
> can any one explain me ..

Hashes themselves aren't sorted so you have to extract the
objects and then sort that list:

class Beans < Struct.new(:description, :weightage); end

b1 = Beans.new('bean 1', 20)
b2 = Beans.new('bean 2', 30)
b3 = Beans.new('bean 3', 25)

collection = { b1.description => b1, b2.description => b2,  
b3.description => b3}

sorted = collection.values.sort_by { |x| x.weightage }
p sorted

[#<struct Beans description="bean 1", weightage=20>, #<struct Beans  
description="bean 3", weightage=25>, #<struct Beans description="bean  
2", weightage=30>]

P.S.  What is a 'bean diagnosis' and 'weightage'?


Gary Wright