From: Garance A Drosehn Date: 2005-07-16T11:08:57+09:00 Subject: Cascading <=> comparisons Let's say I have a hash with some values in it, and I want to print out that hash in some sort order. I can: korder = vals.keys.sort { |ka, kb| vals[kb] <=> vals[ka] } korder.each { |key| printf " %3d - %s\n", vals[key], key } That's pretty easy, but what if I want to cascade comparisons in that sort, such that if the data-values are equal, then I want the sort order to be based on some other comparison? It seems to me that I have to: korder = vals.keys.sort { |ka, kb| sres = vals[kb] <=> vals[ka] sres = ka <=> kb if sres == 0 sres } korder.each { |key| printf " %3d - %s\n", vals[key], key } In perl, I can just casade the '<=>' comparisons, because it will treat the zero value as "false". Thus, I could get away with a one-liner somewhat similar to: vals[kb] <=> vals[ka] or a <=> kb but that doesn't work in ruby. Is there some other way I could collapse multiple <=> comparisons into a single statement? I do not mind the multi-statement form (now that I've convinced myself that I can't cascade them the way I could in perl), but I'm just wondering if there's a better way to do it. -- Garance Alistair Drosehn = drosihn@gmail.com Senior Systems Programmer or gad@FreeBSD.org Rensselaer Polytechnic Institute; Troy, NY; USA