Sorting with Hash

Sorry, after reading your post again I guess I haven't
understand your problem.

Standard Hashes are not sorted, never. If you call
sort on a Hash you get nested arrays.

[["a", 10], ["b", 30], ["c", 20]]

if you want to iterate over this array just use each.

c.each{|k, v| do_something(k, v)}

if you want the value corresponding to a key use assoc.

c.assoc('b') #=> 30

(but this is slow on large arrays)

Hth

Simon

···

-----Original Message-----
From: Kroeger, Simon (ext)
Sent: Thursday, April 27, 2006 3:10 PM
To: ruby-talk ML
Subject: Re: Sorting with Hash

Hi Dinesh!

h = { "c" => 20, "b" => 30, "a" => 10 }
c = h.keys.sort.map{|k| [k, h[k]]}

puts c
puts '======='
puts c[0]

cheers

Simon

> -----Original Message-----
> From: list-bounce@example.com
> [mailto:list-bounce@example.com] On Behalf Of Dinesh Umanath
> Sent: Thursday, April 27, 2006 2:52 PM
> To: ruby-talk ML
> Subject: Sorting with Hash
>
> Hi all,
>
> I have a hash like this and i want to sort. After sorting i
> want the key
> and value seperately. like say
>
> c=Hash.new
> h = { "c" => 20, "b" => 30, "a" => 10 }
>
> c = h.sort
> puts c
> ====>which will result in
> a
> 10
> b
> 30
> c
> 20
>
> puts c[0]
> ===>which will result in
> a
> 10
>
> Now after we have sorted i want to fetch the individual
> key/value like
> we know 'a' is the key and 10 is the value above. How can
we get them
> individually (key/value after we sort) any methods are there
> ? pl help
> me out..
>
> We are storing the sorted result in another hash c.
>
> Can we get the individual key/value pairs from this c. (which
> is sorted)
> ??
>
> Or is there any other other way to do ?
>
> Thank You.
> Dinesh
>
>
>
> --
> Posted via http://www.ruby-forum.com/\.
>
>