From: Aleksandar Lazic Date: 2006-10-30T00:20:35+09:00 Subject: Re: How can i do 'foreach (reverse sort { $hasref->{$a} <=> $hasref->{$b} } keys %{$hasref})..' in ruby On Mon 30.10.2006 00:10, Robert Klemme wrote: >Aleksandar Lazic wrote: > >>but it looks to me that sort give me only a array back. > >Yes, it does - even if you sort the hash. But that's natural as a Hash >has no order so returning a Hash would not make sense. Yep, ;-). >>Here my perl code which i want to translate: >> >>foreach (reverse sort { $hasref->{$a} <=> $hasref->{$b} } keys >> %{$hasref}){ printf("% 7i %s\n",$hasref->{$_}, $_); >> #^^^^^^^Key output ^^value output >>} > >If you want to reverse sort a Hash by values you can do > >sorted = hash.sort {|(k1,v1),(k2,v2)| v2 <=> v1} > >You can iterate "sorted" like a hash: > >sorted.each {|k,v| print key, " => ", value, "\n"} > >In some cases you can use sort_by: > >irb(main):001:0> {1=>2,3=>4}.sort_by {|k,v| -v} >=> [[3, 4], [1, 2]] Many thanks the '|(k1,v1),(k2,v2)|' I haven't know. For the archive: My working line is know: clients.sort{|(k1,v1),(k2,v2)| v2 <=> v1}.each{|k,v| printf("% 7i %s\n",v, k) } Regards Aleks