Brian Candler <B.Candler / pobox.com> wrote in message news:<20030701112013.A20127 / linnet.org>...
> On Tue, Jul 01, 2003 at 07:07:55PM +0900, Osuka wrote:
> > I'm Having some trouble sorting a hash!, the hash contents are like
> > this:
> > 
> > 1 is Ayumi Hamasaki
> > 2 is Zone
> > 1 is Two-Mix
> > 2 is Shazna
> > 1 is L'arc~en~ciel
> 
> I don't understand. Firstly, do you mean that your hash is like this:
> 
>   myhash = {
> 	'Ayumi Hamasaki' => 1,
> 	'Zone' => 2,
> 	'Two-Mix' => 1,
> 	'Shazna' => 2,
> 	'L\'Arc~en~ciel' => 1,
>   }
> 
Sorry about that!! but you got the right idea!!

> Secondly, how do you want to sort it? If you just do
> 
>    myhash.sort
> 
> then you will get it sorted alphabetically by the key, i.e.
> 
> => [["Ayumi Hamasaki", 1], ["L'Arc~en~ciel", 1], ["Shazna", 2],
>     ["Two-Mix", 1], ["Zone", 2]]
> 
> If you want to sort it by the numeric value, then you can pass in an
> explicit block which shows how to compare the values:
> 
>   myhash.sort {|x,y| x[1] <=> y[1]}
> 
> => [["Ayumi Hamasaki", 1], ["L'Arc~en~ciel", 1], ["Two-Mix", 1],
>     ["Shazna", 2], ["Zone", 2]]
> 
> (you can see all the 1's come before the 2's)

Arrg I did tried this and the to_a approach but i forgot something way
too simple! if myhash.sort {|x,y| x[1] <=> y[1]} does return the
sorted array but doesn't actually affects the given array so I have to
assign the returned value to the hash I'm using, how come I miss it!!!
all the problem was here!!

Yes I want it sorted by descending values not alphabetical
[["Shazna", 2],["Zone", 2],["Ayumi Hamasaki", 1], ["L'Arc~en~ciel",
1], ["Two-Mix", 1]]

> 
> Essentially the thing to remember is: when you sort a hash, it first gets
> converted to an array, where each element is a two-element array of
> [key,value] pairs.
> 
> You can do this conversion yourself explicitly:
> 
>   myhash.to_a
> 
> > Problem is: I want to ordered it in a descending order but using
> > Hash.invert I lose data 'cos there can't be several keys that are the
> > same, so any ideas of how to do this
> 
> By descending order of what?
> 
> Hash.invert doesn't reverse the order of elements, it swaps the keys and the
> values!! If you want a reverse alphabetical sort, try:
> 
>   myhash.sort.reverse
> 
> => [["Zone", 2], ["Two-Mix", 1], ["Shazna", 2], ["L'Arc~en~ciel", 1],
>     ["Ayumi Hamasaki", 1]]
> 

yes values become keys and keys values, that's why it was "working"
but eliminating some new keys ie duplicated ones. doing a reverse then
converting to an array meaned that I could easily get it sorted as I
wanted but I would lose elements because of key duplicates, which its
my fault for not considering that a lot of the values are identical.
> Regards,
> 
> Brian.

well thanks!! now it works and sorry for a not so clear post.