From: dblack@... Date: 2006-01-04T22:24:15+09:00 Subject: Re: Newbie question about nested sort Hi -- On Wed, 4 Jan 2006, Grehom wrote: > what am I doing wrong? I wanted to sort primarily on count (second > position in array), then sub-sort alphabetically (first position in > array) > > char_freq = [["c", 2],["b", 5],["a", 2]] > sorted_freq = char_freq.sort {|a, b| b[1]<=>a[1] || a[0]<=>b[0] } > sorted_freq.each do |d| > print d[0]*d[1] > end > > produces >> bbbbbccaa > > when I was rather hoping for >> bbbbbaacc Since 0 is true in Ruby (unlike Perl, where it's false), the || test will never be performed, because b[1] <=> a[1] is always true. You can use sort_by, though: sorted_freq = char_freq.sort_by {|a| [-a[1], a[0]] } (You can also do explicit tests for a 0 result, but sort_by is much more concise.) David -- David A. Black dblack@wobblini.net "Ruby for Rails", from Manning Publications, coming April 2006! http://www.manning.com/books/black