sorting a hash based on a attribute of teh objects which it

S

senthil

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 ..

thanks and regards,
senthil kumar
 
R

Robert Dober

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 ..

thanks and regards,
senthil kumar
Hashes do not define any order by definition (in Ruby), please search
the list for implementations of "ordered Maps/Dictionaries/Hashes"
this is a VFAQ.

If you can take the time to convert your hash to a sorted array of
pairs you can something like this of course.

hash.to_a.sort{ |h1, h2|
h1.first.whatever <=> h2.first.whatever # for keys
or
h1.last.whatelse <=> h2.last.whateles # for values
}

HTH
Robert
 
G

Gary Wright

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top