From: Robert Klemme Date: 2006-10-30T00:10:24+09:00 Subject: Re: How can i do 'foreach (reverse sort { $hasref->{$a} <=> $hasref->{$b} } keys %{$hasref})..' in ruby Aleksandar Lazic wrote: > Hi, > > I'am new with ruby and want to migrate some of my perlscripts to ruby > ;-). > I have a problem with the 'reverse sort' of values of a hashref and > hope that sombody can help me or point me to the right way ;-) > > I have found the a nice answer > http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/30322 > > and have try the follwoing commands: > > clients.values.sort{|a,b| a[1] <=> b[1]}.each {|k,v| > puts "#{k} => #{v}" > } > > clients.values.sort.reverse.each { |k| > puts "#{k}" > } Both of these sort values only! > 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. > 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]] Kind regards robert