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
On 3/13/07, senthil [email protected] wrote:
–
Posted via http://www.ruby-forum.com/.
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
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 W.
Gary W. wrote:
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 .
…
P.S. What is a ‘bean diagnosis’ and ‘weightage’?
Quality control in the Jelly Belly factory?