From: "Simon Kröger" Date: 2006-04-14T19:49:29+09:00 Subject: Re: Rubyesque way to do multiple <=> Victor Shepelev schrieb: >>> def <=> (other) >>> res = ComplexCustomComparator.compare(sex, other.sex) >>> return res if res != 0 >>> >>> #if they have the same sex, do other comparisons >>> end >>> >>> Foooooo! >>> >>> How can I do the former in more elegant way? >>> >>> >> def <=> (other) >> ComplexCustomComparator1.compare(sex, other.sex).nonzero? || >> ComplexCustomComparator2.compare(age, other.age).nonzero? || >> # ... >> ComplexCustomComparatorn.compare(foo, other.foo) >> end > > Seems that return value would be wrong (true/false instead of -1|0|1) > > Victor. from http://www.ruby-doc.org/core/classes/Numeric.html#M001317 --------------------------------------------------------------------- num.nonzero? => num or nil Returns num if num is not zero, nil otherwise. This behavior is useful when chaining comparisons: a = %w( z Bb bB bb BB a aA Aa AA A ) b = a.sort {|a,b| (a.downcase <=> b.downcase).nonzero? || a <=> b } b #=> ["A", "a", "AA", "Aa", "aA", "BB", "Bb", "bB", "bb", "z"] --------------------------------------------------------------------- cheers Simon