# How does sort work on hash

**URL:** <https://www.ruby-forum.com/t/how-does-sort-work-on-hash/65559>\
**Category:** Ruby\
**Created:** [August 19, 2006, 8:54am UTC](https://www.ruby-forum.com/t/how-does-sort-work-on-hash/65559 "2006-08-19T08:54:22Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![hemant\_kumar](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/46a35a/32.png) [@hemant\_kumar](https://www.ruby-forum.com/u/hemant_kumar)\
**Post date:** [August 19, 2006, 8:54am UTC](https://www.ruby-forum.com/t/how-does-sort-work-on-hash/65559/1 "2006-08-19T08:54:22Z")

</div>

I am just a little curious about how exactly sort workes on hashes.

for example:  
a = {:foo =\> 10,:bar =\> 5,:duh =\> 20}

a.sort {|x,y| y[1] \<=\> x[1]}

now how exactly the above line works.the block is passed two elements at  
a  
time, as array? If yes, how sort treates the next two elements?

what algorithm this sort is based on? Is it inplace sorting? or only  
sort!  
does inplace sorting?

May be the question is not so much about hashes.

---

<div class="post-metadata">

**Author:** ![hemant\_kumar](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/46a35a/32.png) [@hemant\_kumar](https://www.ruby-forum.com/u/hemant_kumar)\
**Post date:** [August 19, 2006, 10:04am UTC](https://www.ruby-forum.com/t/how-does-sort-work-on-hash/65559/2 "2006-08-19T10:04:26Z")

</div>

On 8/19/06, hemant kumar [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> I am just a little curious about how exactly sort workes on hashes.
> 
> for example:  
> a = {:foo =\> 10,:bar =\> 5,:duh =\> 20}
> 
> a.sort {|x,y| y[1] \<=\> x[1]}

x and y represent the key, value pairs of the hash and therefore you  
sort by  
values, descending order…

now how exactly the above line works.the block is passed two elements at  
a

> time, as array? If yes, how sort treates the next two elements?

… there are no _next two elements_ the block just tells ruby how to  
compare any two key, value pairs. Ruby than applies a sorting algorithm  
internally…

what algorithm this sort is based on? Is it inplace sorting? or only  
sort!

does inplace sorting?

An array is created from the hash which is sorted by quicksort with the  
criteria indicated above

May be the question is not so much about hashes.

Exactly, the question is about Enumerations.

Hope that helps  
Robert

–  
Deux choses sont infinies : l’univers et la bÃªtise humaine ; en ce qui  
concerne l’univers, je n’en ai pas acquis la certitude absolue.

- Albert Einstein
