From: Eric Mahurin Date: 2005-07-16T11:58:54+09:00 Subject: Re: Cascading <=> comparisons --- Garance A Drosehn wrote: > 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. (vals[kb] <=> vals[ka]).nonzero? or a <=> kb ____________________________________________________ Start your day with Yahoo! - make it your home page http://www.yahoo.com/r/hs